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
|
package core
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
"time"
"github.com/dimonomid/nerdlog/core/testutils"
"github.com/dimonomid/nerdlog/util/sysloggen"
"github.com/juju/errors"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
const agentTestOutputRoot = "/tmp/nerdlog_agent_test_output"
const agentTestCaseYamlFname = "test_case.yaml"
type AgentTestCaseYaml struct {
// If Disabled is true, the test case is skipped.
Disabled bool `yaml:"disabled"`
Descr string `yaml:"descr"`
Logfiles testutils.TestCaseLogfiles `yaml:"logfiles"`
// CurYear and CurMonth specify today's date. If not specified, 1970-01 will
// be used. This matters for inferring the log's year (because traditional
// syslog timestamp format doesn't include year).
CurYear int `yaml:"cur_year"`
CurMonth int `yaml:"cur_month"`
// Env can contain extra environment variables to set, in the format
// VARIABLE=VALUE. It'll be passed to cmd.Env directly.
Env []string `yaml:"env"`
Args []string `yaml:"args"`
}
func TestNerdlogAgent(t *testing.T) {
_, filename, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("unable to get caller info")
}
// Get directory of the current file
parentDir := filepath.Dir(filename)
testCasesDir := filepath.Join(parentDir, "core_testdata", "test_cases_agent")
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
repoRoot := filepath.Dir(filepath.Dir(filename))
if err := os.MkdirAll(agentTestOutputRoot, 0755); err != nil {
t.Fatalf("unable to create agent test output root dir %s: %s", agentTestOutputRoot, err.Error())
}
testCaseDirs, err := testutils.GetTestCaseDirs(testCasesDir, agentTestCaseYamlFname)
if err != nil {
panic(err)
}
for _, testCaseDir := range testCaseDirs {
t.Run(testCaseDir, func(t *testing.T) {
if err := runAgentTestCase(t, nerdlogAgentShFname, testCasesDir, repoRoot, testCaseDir); err != nil {
t.Fatalf("running agent test case %s: %s", testCaseDir, err.Error())
}
})
}
}
func runAgentTestCase(t *testing.T, nerdlogAgentShFname, testCasesDir, repoRoot, testName string) error {
testCaseDir := filepath.Join(testCasesDir, testName)
testCaseDescrFname := filepath.Join(testCaseDir, agentTestCaseYamlFname)
testOutputDir := filepath.Join(agentTestOutputRoot, testName)
if err := os.MkdirAll(testOutputDir, 0755); err != nil {
return errors.Annotatef(err, "unable to create test output dir %s", testOutputDir)
}
data, err := os.ReadFile(testCaseDescrFname)
if err != nil {
return errors.Annotatef(err, "reading yaml test case descriptor %s", testCaseDescrFname)
}
var tc AgentTestCaseYaml
if err := yaml.Unmarshal(data, &tc); err != nil {
return errors.Annotatef(err, "unmarshaling yaml from %s", testCaseDescrFname)
}
if tc.Disabled {
fmt.Printf("WARNING: Skipping %s since it's disabled\n", testName)
return nil
}
resolved, err := testutils.ResolveLogfiles(testCaseDir, &tc.Logfiles)
if err != nil {
return errors.Annotatef(err, "resolving logfiles")
}
provisioned, err := testutils.ProvisionLogFiles(resolved, testOutputDir, repoRoot)
if err != nil {
return errors.Annotatef(err, "provisioning logfiles")
}
indexFname := filepath.Join(testOutputDir, "nerdlog_agent_index")
os.Remove(indexFname)
cmdArgs := []string{
nerdlogAgentShFname,
"query",
"--logfile-last", provisioned.LogfileLast,
"--logfile-prev", provisioned.LogfilePrev,
"--index-file", indexFname,
}
if provisioned.LogfileLast == "journalctl" {
// Specify time format (normally LStreamClient autodetects the time format
// and provides these).
cmdArgs = append(
cmdArgs,
"--awktime-month", "substr($0, 6, 2)",
"--awktime-year", "substr($0, 1, 4)",
"--awktime-day", "substr($0, 9, 2)",
"--awktime-hhmm", "substr($0, 12, 5)",
"--awktime-minute-key", "substr($0, 6, 11)",
)
}
cmdArgs = append(cmdArgs, tc.Args...)
// Do the full run, with the provided initial index (which in most cases
// means, without any index)
if err := runNerdlogAgent(t, &tc, cmdArgs, testCaseDir, provisioned.ExtraEnv, testName, testNerdlogAgentParams{
checkStderr: true,
}); err != nil {
return errors.Trace(err)
}
// For journalctl tests, there is no index, and therefore nothing else to do.
if provisioned.LogfileLast == "journalctl" {
return nil
}
// For log files tests, we rerun the test multiple times after removing some
// latest lines from the index, expecting it to index up and to produce the same
// result.
// If asked to skip these repetitions with indexing up, we're done.
//
// There are at least two valid reasons to skip:
//
// - When we're running "make update-test-expectations", because for that we
// need to capture stderr after the main test (without repetitions), since
// stderr will be different otherwise
// - To run tests much faster (these repetitions are the slowest part of tests)
if os.Getenv("NERDLOG_AGENT_TEST_SKIP_INDEX_UP") != "" {
return nil
}
// indexReduceStep specifies how many lines we remove from the index at every
// step here. For most tests, it's 25.
indexReduceStep := 25
// For the tests of handling decreased timestamps, reduce the index by a single
// line, to make sure that some corner case doesn't slip through.
if strings.Contains(testName, "decreased") {
indexReduceStep = 1
}
// Backup the resulting fully-built index
indexFullFname := filepath.Join(testOutputDir, "nerdlog_agent_index_full")
if err := testutils.CopyFile(indexFname, indexFullFname); err != nil {
return errors.Annotatef(err, "backing up index as full index: from %s to %s", indexFname, indexFullFname)
}
// Now, keep running the same query with smaller index: on every iteration,
// we'll remove one more line from the index end, and expect the same stdout
// (not stderr though, this one will be different).
numLines, err := getNumLines(indexFullFname)
if err != nil {
return errors.Annotatef(err, "getting numer of lines in %s", indexFullFname)
}
// We can only remove the "idx" lines from the index.
minLineno, err := getLastNonMatchingLine(indexFullFname, "idx")
if err != nil {
return errors.Annotatef(err, "getLastNonMatchingLine")
}
// minLineno points to the line containing the last non-"idx" entry, but
// we actually need at least one "idx" entry in the index file for it to work,
// so we increment it.
minLineno += 1
for keepLines := numLines - 1; ; keepLines -= indexReduceStep {
// If we step too much below the min, use the min (and we'll break below).
if keepLines < minLineno {
keepLines = minLineno
}
_, err := copyUpToNumLines(indexFullFname, indexFname, keepLines)
if err != nil {
return errors.Annotatef(
err, "copying up to %d lines from %s to %s",
keepLines, indexFullFname, indexFname,
)
}
t.Run(fmt.Sprintf("keep_%d_lines", keepLines), func(t *testing.T) {
if err := runNerdlogAgent(t, &tc, cmdArgs, testCaseDir, provisioned.ExtraEnv, testName, testNerdlogAgentParams{
// When changing the index, stderr would change too.
checkStderr: false,
}); err != nil {
t.Fatalf("error: %s", err.Error())
}
})
if keepLines <= minLineno {
break
}
}
// TODO: the stats lines in stdout (these starting from "s:") are printed in
// arbitrary order because they come from a hashmap, so simply comparing the
// output is a bad idea. Gotta do some post-processing, like sorting these "s:"
// lines, before comparing them.
return nil
}
type testNerdlogAgentParams struct {
checkStderr bool
}
func runNerdlogAgent(
t *testing.T, tc *AgentTestCaseYaml, bashArgs []string, testCaseDir string,
extraEnv []string,
testName string,
params testNerdlogAgentParams,
) error {
assertArgs := []interface{}{"test case %s", testName}
testOutputDir := filepath.Join(agentTestOutputRoot, testName)
stdoutFname := filepath.Join(testOutputDir, "nerdlog_agent_stdout")
stderrFname := filepath.Join(testOutputDir, "nerdlog_agent_stderr")
os.Remove(stdoutFname)
os.Remove(stderrFname)
stdoutFile, err := os.Create(stdoutFname)
defer stdoutFile.Close()
stderrFile, err := os.Create(stderrFname)
defer stderrFile.Close()
cmd := exec.Command("/usr/bin/env", append([]string{"bash"}, bashArgs...)...)
curYear := tc.CurYear
if curYear == 0 {
curYear = 1970
}
curMonth := tc.CurMonth
if curMonth == 0 {
curMonth = 1
}
agentEnv := []string{
"TZ=UTC",
fmt.Sprintf("CUR_YEAR=%d", curYear),
fmt.Sprintf("CUR_MONTH=%d", curMonth),
}
agentEnv = append(agentEnv, tc.Env...)
agentEnv = append(agentEnv, extraEnv...)
cmd.Env = append(
os.Environ(),
agentEnv...,
)
cmd.Stdout = stdoutFile
cmd.Stderr = stderrFile
fmt.Printf("Running %+v\n", bashArgs)
if err := cmd.Run(); err != nil {
return errors.Annotatef(err, "running nerdlog query command %+v", bashArgs)
}
wantStdout, err := os.ReadFile(filepath.Join(testCaseDir, "want_stdout"))
if err != nil {
return errors.Annotatef(err, "reading want_stdout")
}
wantStderr, err := os.ReadFile(filepath.Join(testCaseDir, "want_stderr"))
if err != nil {
return errors.Annotatef(err, "reading want_stderr")
}
if err := sortStatBucketLinesInFile(stdoutFname); err != nil {
return errors.Annotatef(err, "transforming stdout %s using sortStatBucketLinesInFile", stdoutFname)
}
gotStdout, err := os.ReadFile(stdoutFname)
if err != nil {
return errors.Annotatef(err, "reading %s", stdoutFname)
}
gotStderr, err := os.ReadFile(stderrFname)
if err != nil {
return errors.Annotatef(err, "reading %s", stderrFname)
}
assert.Equal(t, string(wantStdout), string(gotStdout), assertArgs...)
if params.checkStderr {
assert.Equal(t, string(wantStderr), string(gotStderr), assertArgs...)
}
return nil
}
// sortStatBucketLines takes a string representing stdout output from the
// nerdlog agent script, like this:
//
// logfile:/tmp/nerdlog_agent_test_output/all_existing_logs/01_from_is_set_to_is_set/logfile.1:0
// logfile:/tmp/nerdlog_agent_test_output/all_existing_logs/01_from_is_set_to_is_set/logfile:19
// s:Mar 10 10:20,2
// s:Mar 10 09:39,1
// s:Mar 10 09:00,1
// s:Mar 10 09:59,1
// s:Mar 10 10:32,2
// m:34:Mar 10 10:51:01 myhost user[3758]: <crit> System running low on resources
// m:35:Mar 10 10:57:37 myhost news[5185]: <alert> Insufficient privileges
// exit_code:0
//
// And returns the same string, but all the lines starting from "s:" being sorted
// lexicographically. This is just for better testability.
func sortStatBucketLines(nerdlogStdout []byte) []byte {
scanner := bufio.NewScanner(bytes.NewReader(nerdlogStdout))
var out bytes.Buffer
var statLines []string
flushStatLines := func() {
if len(statLines) > 0 {
sort.Strings(statLines)
for _, line := range statLines {
out.WriteString(line)
out.WriteByte('\n')
}
statLines = nil
}
}
for scanner.Scan() {
line := scanner.Text()
if len(line) > 2 && line[:2] == "s:" {
statLines = append(statLines, line)
} else {
flushStatLines()
out.WriteString(line)
out.WriteByte('\n')
}
}
flushStatLines() // in case the input ends with s: lines
return out.Bytes()
}
// sortStatBucketLinesInFile reads all file contents using the given filename,
// transforms it using sortStatBucketLines, and writes back to the same file.
func sortStatBucketLinesInFile(fname string) error {
data, err := os.ReadFile(fname)
if err != nil {
return errors.Annotatef(err, "reading in sortStatBucketLinesInFile")
}
sorted := sortStatBucketLines(data)
err = os.WriteFile(fname, sorted, 0644)
if err != nil {
return errors.Annotatef(err, "writing in sortStatBucketLinesInFile")
}
return nil
}
func runNerdlogAgentForBenchmark(
bashArgs []string,
) error {
cmd := exec.Command("/usr/bin/env", append([]string{"bash"}, bashArgs...)...)
cmd.Env = append(os.Environ(), "TZ=UTC")
if err := cmd.Run(); err != nil {
return errors.Annotatef(err, "running nerdlog query command %+v", bashArgs)
}
return nil
}
// getNumLines returns the number of lines in the given file.
func getNumLines(fname string) (int, error) {
file, err := os.Open(fname)
if err != nil {
return 0, errors.Annotatef(err, "failed to open file %q", fname)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineCount := 0
for scanner.Scan() {
lineCount++
}
if err := scanner.Err(); err != nil {
return 0, errors.Annotate(err, "error while scanning file")
}
return lineCount, nil
}
// getLastNonMatchingLine returns the number of the last line which does not start
// with the given string. Line numbers are 1-based.
func getLastNonMatchingLine(fname string, prefix string) (int, error) {
file, err := os.Open(fname)
if err != nil {
return 0, errors.Annotatef(err, "failed to open file: %s", fname)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineNumber := 0
lastNonMatchingLine := 0
for scanner.Scan() {
lineNumber++
line := scanner.Text()
if !strings.HasPrefix(line, prefix) {
lastNonMatchingLine = lineNumber
}
}
if err := scanner.Err(); err != nil {
return 0, errors.Annotate(err, "error scanning file")
}
return lastNonMatchingLine, nil
}
// copyUpToNumLines copies srcPath as destPath, but only the first maxNumLines.
// It returns the last line.
func copyUpToNumLines(srcPath, destPath string, maxNumLines int) (string, error) {
srcFile, err := os.Open(srcPath)
if err != nil {
return "", errors.Annotatef(err, "failed to open source file: %s", srcPath)
}
defer srcFile.Close()
destFile, err := os.Create(destPath)
if err != nil {
return "", errors.Annotatef(err, "failed to create destination file: %s", destPath)
}
defer destFile.Close()
scanner := bufio.NewScanner(srcFile)
writer := bufio.NewWriter(destFile)
defer writer.Flush()
var lastLine string
lineCount := 0
for scanner.Scan() {
line := scanner.Text()
if lineCount < maxNumLines {
_, err := writer.WriteString(line + "\n")
if err != nil {
return "", errors.Annotate(err, "failed to write line to destination file")
}
}
lastLine = line
lineCount++
if lineCount >= maxNumLines {
break
}
}
if err := scanner.Err(); err != nil {
return "", errors.Annotate(err, "error while scanning source file")
}
return lastLine, nil
}
func BenchmarkNerdlogAgentSmallLogNoIndex(b *testing.B) {
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
logfilesDir := filepath.Join(parentDir, "core_testdata", "input_logfiles", "small_mar")
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench1_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", filepath.Join(logfilesDir, "syslog"),
"--logfile-prev", filepath.Join(logfilesDir, "syslog.1"),
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-12-10:00",
},
)
b.ResetTimer()
for i := 0; i < b.N; i++ {
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func BenchmarkNerdlogAgentSmallLogCompleteIndex(b *testing.B) {
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
logfilesDir := filepath.Join(parentDir, "core_testdata", "input_logfiles", "small_mar")
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench1_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", filepath.Join(logfilesDir, "syslog"),
"--logfile-prev", filepath.Join(logfilesDir, "syslog.1"),
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-12-10:00",
},
)
// Build the index
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func BenchmarkNerdlogAgentLargeLogSmallPortionNoIndex(b *testing.B) {
if err := generateLogfilesLarge(); err != nil {
b.Fatalf("failed to generate log files: %s", err.Error())
}
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
"--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-11-00:00",
},
)
b.ResetTimer()
for i := 0; i < b.N; i++ {
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func BenchmarkNerdlogAgentLargeLogSmallPortionCompleteIndex(b *testing.B) {
if err := generateLogfilesLarge(); err != nil {
b.Fatalf("failed to generate log files: %s", err.Error())
}
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
"--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-11-00:00",
},
)
// Build the index
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func BenchmarkNerdlogAgentLargeLogTinyPortionCompleteIndex(b *testing.B) {
if err := generateLogfilesLarge(); err != nil {
b.Fatalf("failed to generate log files: %s", err.Error())
}
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
"--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-11-01:30",
},
)
// Build the index
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func BenchmarkNerdlogAgentHugeLogOneHourCompleteIndex(b *testing.B) {
if err := generateLogfilesHuge(); err != nil {
b.Fatalf("failed to generate log files: %s", err.Error())
}
_, filename, _, ok := runtime.Caller(0)
if !ok {
b.Fatal("unable to get caller info")
}
parentDir := filepath.Dir(filename)
nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
indexFname := filepath.Join(agentTestOutputRoot, "bench_huge_index")
cmdArgs := append(
[]string{
nerdlogAgentShFname,
"query",
"--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_huge",
"--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_huge.1",
"--index-file", indexFname,
"--max-num-lines", "100",
"--from", "2025-03-11-12:30",
},
)
// Build the index
os.Remove(indexFname)
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
}
}
}
func generateLogfilesLarge() error {
t, err := time.Parse(time.RFC3339, "2025-03-09T06:00:00Z")
if err != nil {
return errors.Trace(err)
}
t2, err := time.Parse(time.RFC3339, "2025-03-10T06:00:00Z")
if err != nil {
return errors.Trace(err)
}
err = sysloggen.GenerateSyslog(sysloggen.Params{
StartTime: t,
SecondLogTime: t2,
LogBasename: "/tmp/nerdlog_agent_test_output/randomlog_large",
NumLogs: 4000000,
MinDelayMS: 0,
MaxDelayMS: 80,
RandomSeed: 123,
SkipIfPrevLogSizeIs: 143841612,
SkipIfLastLogSizeIs: 122432250,
})
if err != nil {
return errors.Trace(err)
}
return nil
}
func generateLogfilesHuge() error {
t, err := time.Parse(time.RFC3339, "2025-03-09T06:00:00Z")
if err != nil {
return errors.Trace(err)
}
t2, err := time.Parse(time.RFC3339, "2025-03-09T09:00:00Z")
if err != nil {
return errors.Trace(err)
}
err = sysloggen.GenerateSyslog(sysloggen.Params{
StartTime: t,
SecondLogTime: t2,
LogBasename: "/tmp/nerdlog_agent_test_output/randomlog_huge",
NumLogs: 40000000,
MinDelayMS: 0,
MaxDelayMS: 10,
RandomSeed: 123,
SkipIfPrevLogSizeIs: 143833610,
SkipIfLastLogSizeIs: 2518973348,
})
if err != nil {
return errors.Trace(err)
}
return nil
}
|