File: core_test.go

package info (click to toggle)
nerdlog 1.10.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,296 kB
  • sloc: sh: 1,004; makefile: 85
file content (590 lines) | stat: -rw-r--r-- 16,821 bytes parent folder | download
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
package core

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"os/user"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/dimonomid/clock"
	"github.com/dimonomid/nerdlog/core/testutils"
	"github.com/dimonomid/nerdlog/log"
	"github.com/juju/errors"
	"github.com/stretchr/testify/assert"
	"gopkg.in/yaml.v2"
)

const coreTestOutputRoot = "/tmp/nerdlog_core_test_output"
const coreTestScenarioYamlFname = "test_scenario.yaml"

type CoreTestScenarioYaml struct {
	Descr string `yaml:"descr"`

	CurrentTime testutils.MyTime `yaml:"current_time"`

	ManagerParams CoreTestScenarioManagerParams `yaml:"manager_params"`
	TestSteps     []CoreTestStep                `yaml:"test_steps"`
}

// CoreTestScenarioManagerParams converts into LStreamsManagerParams.
type CoreTestScenarioManagerParams struct {
	ConfigLogStreams map[string]CoreTestConfigLogStream `yaml:"config_log_streams"`

	InitialLStreams string `yaml:"initial_lstreams"`
	ClientID        string `yaml:"client_id"`
}

// CoreTestConfigLogStream converts to ConfigLogStream (from config.go)
type CoreTestConfigLogStream struct {
	LogFiles testutils.TestCaseLogfiles `yaml:"log_files"`

	Options ConfigLogStreamOptions `yaml:"options"`
}

type CoreTestStep struct {
	// Descr is a human-readable step description
	Descr string `yaml:"descr"`

	// Exactly one of the fields below must be non-nil

	CheckState *CoreTestStepCheckState `yaml:"check_state"`

	// If Query is non-nil, we'll send a query to the LStreamsManager.
	Query *CoreTestStepQuery `yaml:"query"`
}

type CoreTestStepCheckState struct {
	// WantByHostnameAndTransport is a map from the test hostname-and-transport
	// string to the filename with the expected LStreamsManagerState.
	//
	// The hostname-and-transport string looks like this:
	//
	// - "localhost": for localhost, it's just this, since there is only one kind
	//   of transport
	// - "127.0.0.1_ssh-lib": for non-localhost hostname without UseExternalSSH
	// - "127.0.0.1_ssh-bin": for non-localhost hostname with UseExternalSSH
	WantByHostnameAndTransport map[string]string `yaml:"want_by_hostname_and_transport"`
}

type CoreTestStepQuery struct {
	Params CoreTestStepQueryParams `yaml:"params"`

	// Want is a filename (relative to the test scenario dir) with the expected
	// results.
	Want string `yaml:"want"`
}

// CoreTestStepQueryParams converts into QueryLogsParams (from core.go).
type CoreTestStepQueryParams struct {
	MaxNumLines int `yaml:"max_num_lines"`

	From testutils.MyTime `yaml:"from"`
	To   testutils.MyTime `yaml:"to"`

	Pattern string `yaml:"pattern"`

	LoadEarlier bool `yaml:"load_earlier"`

	RefreshIndex bool `yaml:"refresh_index"`
}

func (p *CoreTestStepQueryParams) RealParams() QueryLogsParams {
	return QueryLogsParams{
		MaxNumLines:  p.MaxNumLines,
		From:         p.From.Time,
		To:           p.To.Time,
		Query:        p.Pattern,
		LoadEarlier:  p.LoadEarlier,
		RefreshIndex: p.RefreshIndex,
	}
}

func TestCoreScenarios(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)
	testScenariosDir := filepath.Join(parentDir, "core_testdata", "test_cases_core")

	repoRoot := filepath.Dir(filepath.Dir(filename))

	if err := os.MkdirAll(coreTestOutputRoot, 0755); err != nil {
		t.Fatalf("unable to create core test output root dir %s: %s", coreTestOutputRoot, err.Error())
	}

	testScenarioDirs, err := testutils.GetTestCaseDirs(testScenariosDir, coreTestScenarioYamlFname)
	if err != nil {
		panic(err)
	}

	for _, testName := range testScenarioDirs {
		t.Run(testName, func(t *testing.T) {
			tsCtx := &coreTestScenarioContext{
				testName:        testName,
				testScenarioDir: filepath.Join(testScenariosDir, testName),
				testOutputDir:   filepath.Join(coreTestOutputRoot, testName),
				repoRoot:        repoRoot,
			}

			if err := runCoreTestScenario(t, tsCtx); err != nil {
				t.Fatalf("running core test scenario %s: %s", testName, err.Error())
			}
		})
	}
}

type coreTestScenarioContext struct {
	testName        string
	testScenarioDir string
	testOutputDir   string
	repoRoot        string
}

func runCoreTestScenario(t *testing.T, tsCtx *coreTestScenarioContext) error {
	testScenarioDescrFname := filepath.Join(tsCtx.testScenarioDir, coreTestScenarioYamlFname)

	if err := os.MkdirAll(tsCtx.testOutputDir, 0755); err != nil {
		return errors.Annotatef(err, "unable to create test output dir %s", tsCtx.testOutputDir)
	}

	data, err := os.ReadFile(testScenarioDescrFname)
	if err != nil {
		return errors.Annotatef(err, "reading yaml test case descriptor %s", testScenarioDescrFname)
	}

	var tc CoreTestScenarioYaml
	if err := yaml.Unmarshal(data, &tc); err != nil {
		return errors.Annotatef(err, "unmarshaling yaml from %s", testScenarioDescrFname)
	}

	if tc.CurrentTime.Time.IsZero() {
		return errors.Annotatef(err, "current_time must not be zero in %s", testScenarioDescrFname)
	}

	clockMock := clock.NewMock()
	clockMock.Set(tc.CurrentTime.Time)

	manTH, err := newLStreamsManagerTestHelper(tc.ManagerParams, tsCtx, clockMock)
	if err != nil {
		return errors.Annotatef(err, "creating LStreamsManagerTestHelper")
	}

	fmt.Println("Waiting connection...")
	manTH.WaitConnected()

	isFirstQuery := true
	for i, step := range tc.TestSteps {
		stepSID := fmt.Sprintf("%.2d_%s", i+1, testutils.Slug(step.Descr))
		stepOutputDir := filepath.Join(tsCtx.testOutputDir, "steps", stepSID)
		if err := os.MkdirAll(stepOutputDir, 0755); err != nil {
			return errors.Annotatef(err, "creating lstream dir %s", stepSID)
		}

		assertArgs := []interface{}{"test case %s", stepSID}

		if checkState := step.CheckState; checkState != nil {
			lsmStateStr := formatLSMState(manTH.GetLSMState())
			err = os.WriteFile(filepath.Join(stepOutputDir, "got_logstreams_manager_state.txt"), []byte(lsmStateStr), 0644)
			if err != nil {
				return errors.Annotatef(err, "test step #%d: writing lsm state", i)
			}

			hostnameAndTransportKey := manTH.getHostnameAndTransportKey()
			wantFilename := checkState.WantByHostnameAndTransport[hostnameAndTransportKey]

			if wantFilename == "" {
				return errors.Errorf("test step #%d: no WantByHostnameAndTransport for %q", i, hostnameAndTransportKey)
			} else {
				err = os.WriteFile(filepath.Join(stepOutputDir, "want_lsm_state_filename.txt"), []byte(wantFilename), 0644)
				if err != nil {
					return errors.Annotatef(err, "test step #%d: writing want_lsm_state_filename.txt", i)
				}

				wantLSMStateFilenameFull := filepath.Join(tsCtx.testScenarioDir, wantFilename)
				wantLSMState, err := os.ReadFile(wantLSMStateFilenameFull)
				if err != nil {
					return errors.Annotatef(err, "test step #%d: reading wanted log resp %s", i, wantLSMStateFilenameFull)
				}

				assert.Equal(t, string(wantLSMState), lsmStateStr, assertArgs...)
			}
		} else if query := step.Query; query != nil {
			// For reproducibility of the exact same debug output, refresh the index
			// during the first query in a scenario.
			if isFirstQuery {
				query.Params.RefreshIndex = true
				isFirstQuery = false
			}

			logResp, err := manTH.QueryLogs(query.Params)
			if err != nil {
				return errors.Annotatef(err, "test step #%d: querying logs %+v", i, query.Params)
			}

			logRespStr := formatLogResp(logResp)
			err = os.WriteFile(filepath.Join(stepOutputDir, "got_log_resp.txt"), []byte(logRespStr), 0644)
			if err != nil {
				return errors.Annotatef(err, "test step #%d: writing log resp", i)
			}

			err = os.WriteFile(filepath.Join(stepOutputDir, "want_log_resp_filename.txt"), []byte(query.Want), 0644)
			if err != nil {
				return errors.Annotatef(err, "test step #%d: writing want_log_resp_filename.txt", i)
			}

			wantLogRespFilenameFull := filepath.Join(tsCtx.testScenarioDir, query.Want)
			wantLogResp, err := os.ReadFile(wantLogRespFilenameFull)
			if err != nil {
				return errors.Annotatef(err, "test step #%d: reading wanted log resp %s", i, wantLogRespFilenameFull)
			}

			assert.Equal(t, string(wantLogResp), logRespStr, assertArgs...)
		}
	}

	fmt.Println("Closing LStreamsManager...")
	if err := manTH.CloseAndWait(); err != nil {
		return errors.Trace(err)
	}

	return nil
}

type LStreamsManagerTestHelper struct {
	manager   *LStreamsManager
	updatesCh chan LStreamsManagerUpdate
	clock     *clock.Mock

	state    LStreamsManagerTestHelperState
	stateMtx sync.Mutex
}

type LStreamsManagerTestHelperState struct {
	lsmState        *LStreamsManagerState
	pendingLogResps []*LogRespTotal
}

func newLStreamsManagerTestHelper(
	params CoreTestScenarioManagerParams,
	tsCtx *coreTestScenarioContext,
	clockMock *clock.Mock,
) (*LStreamsManagerTestHelper, error) {
	updatesCh := make(chan LStreamsManagerUpdate, 100)

	cfgLogStreams := make(ConfigLogStreams, len(params.ConfigLogStreams))
	for lstreamName, testCfg := range params.ConfigLogStreams {
		resolved, err := testutils.ResolveLogfiles(tsCtx.testScenarioDir, &testCfg.LogFiles)
		if err != nil {
			return nil, errors.Annotatef(err, "resolving logfiles")
		}

		testOutputLstreamDir := filepath.Join(tsCtx.testOutputDir, "lstreams", lstreamName)
		if err := os.MkdirAll(testOutputLstreamDir, 0755); err != nil {
			return nil, errors.Annotatef(err, "creating lstream dir %s", lstreamName)
		}

		provisioned, err := testutils.ProvisionLogFiles(
			resolved,
			testOutputLstreamDir,
			tsCtx.repoRoot,
		)
		if err != nil {
			return nil, errors.Annotatef(err, "provisioning logfiles")
		}

		options := testCfg.Options
		for _, envVar := range provisioned.ExtraEnv {
			options.ShellInit = append(options.ShellInit, fmt.Sprintf("export %s", envVar))
		}

		cfgLogStreams[lstreamName] = ConfigLogStream{
			Hostname: getCoreTestHostname(),
			LogFiles: []string{
				provisioned.LogfileLast,
				provisioned.LogfilePrev,
			},
			Options: options,
		}
	}

	manParams := LStreamsManagerParams{
		ConfigLogStreams: cfgLogStreams,
		Logger:           log.NewLogger(log.Verbose1).WithStdout(true),
		InitialLStreams:  params.InitialLStreams,
		ClientID:         params.ClientID,
		UpdatesCh:        updatesCh,
		Clock:            clockMock,

		InitialUseExternalSSH: os.Getenv("NERDLOG_CORE_TEST_TRANSPORT_SSH_BIN") != "",
	}

	fmt.Println("Creating LStreamsManager...")
	manager := NewLStreamsManager(manParams)

	manTH := &LStreamsManagerTestHelper{
		manager:   manager,
		updatesCh: updatesCh,
		clock:     clockMock,
	}

	go manTH.run()

	return manTH, nil
}

// getCoreTestHostname finds out the hostname: normally we use just
// `localhost`, which means we'll use ShellTransportLocal, but it can be
// overridden with the NERDLOG_CORE_TEST_HOSTNAME env var. Keep in mind that
// only `localhost` bypasses ssh; so e.g. "127.0.0.1" will use
// ShellTransportSSH, and we can take advantage of that to cover the ssh
// transport in tests. Obviously, for that the ssh server needs to be running
// locally.
func getCoreTestHostname() string {
	hostname := os.Getenv("NERDLOG_CORE_TEST_HOSTNAME")
	if hostname == "" {
		hostname = "localhost"
	}

	return hostname
}

func (th *LStreamsManagerTestHelper) getHostnameAndTransportKey() string {
	testHostname := getCoreTestHostname()
	if testHostname == "localhost" {
		return testHostname
	}

	useExternalSSH := th.manager.useExternalSSH
	transportStr := "ssh-lib"
	if useExternalSSH {
		transportStr = "ssh-bin"
	}

	return fmt.Sprintf("%s_%s", testHostname, transportStr)
}

func (th *LStreamsManagerTestHelper) run() {
	for upd := range th.updatesCh {
		th.applyUpdate(upd)
	}
}

func (th *LStreamsManagerTestHelper) applyUpdate(upd LStreamsManagerUpdate) {
	//d, _ := json.Marshal(upd)
	//fmt.Printf("    UPD: %s\n", string(d))

	th.stateMtx.Lock()
	defer th.stateMtx.Unlock()

	if upd.State != nil {
		th.state.lsmState = upd.State
	} else if upd.LogResp != nil {
		th.state.pendingLogResps = append(th.state.pendingLogResps, upd.LogResp)
	}
}

func (th *LStreamsManagerTestHelper) isConnected() bool {
	th.stateMtx.Lock()
	defer th.stateMtx.Unlock()

	return th.state.lsmState != nil && th.state.lsmState.Connected
}

func (th *LStreamsManagerTestHelper) nextLogResp() *LogRespTotal {
	th.stateMtx.Lock()
	defer th.stateMtx.Unlock()

	if len(th.state.pendingLogResps) == 0 {
		return nil
	}

	ret := th.state.pendingLogResps[0]
	th.state.pendingLogResps = th.state.pendingLogResps[1:]

	return ret
}

func (th *LStreamsManagerTestHelper) WaitConnected() {
	for {
		if th.isConnected() {
			return
		}

		// TODO: We could implement subscribing to state updates, but for now just polling.
		time.Sleep(100 * time.Millisecond)
	}
}

func (th *LStreamsManagerTestHelper) QueryLogs(params CoreTestStepQueryParams) (*LogRespTotal, error) {
	// Sanity check that there is no existing pending log resp
	existing := th.nextLogResp()
	if existing != nil {
		return existing, errors.Errorf("there was existing pending log resp")
	}

	th.manager.QueryLogs(params.RealParams())

	return th.WaitNextLogResp()
}

func (th *LStreamsManagerTestHelper) GetLSMState() *LStreamsManagerState {
	return th.state.lsmState
}

func (th *LStreamsManagerTestHelper) WaitNextLogResp() (*LogRespTotal, error) {
	start := time.Now()

	for {
		ret := th.nextLogResp()
		if ret != nil {
			return ret, nil
		}

		if time.Since(start) > 5*time.Second {
			return nil, errors.Errorf("timed out waiting for log resp")
		}

		// TODO: We could implement subscribing to state updates, but for now just polling.
		time.Sleep(100 * time.Millisecond)
	}
}

func (th *LStreamsManagerTestHelper) CloseAndWait() error {
	th.manager.Close()

	closedCh := make(chan struct{})
	go func() {
		th.manager.Wait()
		close(closedCh)
	}()

	select {
	case <-closedCh:
		// All good
		return nil
	case <-time.After(5 * time.Second):
		return errors.Errorf("timed out waiting for LStreamsManager to close")
	}
}

func formatLogResp(logResp *LogRespTotal) string {
	var sb strings.Builder

	sb.WriteString(fmt.Sprintf("NumMsgsTotal: %v\n", logResp.NumMsgsTotal))
	sb.WriteString(fmt.Sprintf("LoadedEarlier: %v\n", logResp.LoadedEarlier))
	sb.WriteString(fmt.Sprintf("Num errors: %v\n", len(logResp.Errs)))
	for _, err := range logResp.Errs {
		sb.WriteString(fmt.Sprintf("- %s", err.Error()))
	}

	sb.WriteString("\n")
	sb.WriteString(fmt.Sprintf("Num MinuteStats: %v\n", len(logResp.MinuteStats)))
	printMinuteStats(&sb, logResp.MinuteStats)

	sb.WriteString("\n")
	sb.WriteString(fmt.Sprintf("Num Logs: %v\n", len(logResp.Logs)))
	printLogs(&sb, logResp.Logs)

	sb.WriteString("\n")
	debugInfoData, _ := json.MarshalIndent(logResp.DebugInfo, "", "  ")
	sb.WriteString(fmt.Sprintf("DebugInfo:\n%s", debugInfoData))

	return sb.String()
}

func formatLSMState(lsmState *LStreamsManagerState) string {
	data, _ := json.MarshalIndent(lsmState, "", "  ")
	str := string(data)

	// We also need to replace the OS username in the payload with a static
	// placeholder, since it can be different.
	str = maskOSUser(str)

	return str
}

// maskOSUser returns a string with all occurrences of the current OS user
// replaced with "__TEST_OS_USER__".
func maskOSUser(s string) string {
	u, err := user.Current()
	if err != nil {
		// Can't determine the user, return the input unchanged
		return s
	}

	re := regexp.MustCompile(`\b` + regexp.QuoteMeta(u.Username) + `\b`)
	return re.ReplaceAllString(s, "__TEST_OS_USER__")
}

func printMinuteStats(w io.Writer, stats map[int64]MinuteStatsItem) {
	// Extract and sort timestamps for consistent output
	timestamps := make([]int64, 0, len(stats))
	for ts := range stats {
		timestamps = append(timestamps, ts)
	}
	sort.Slice(timestamps, func(i, j int) bool {
		return timestamps[i] < timestamps[j]
	})

	// Print each item
	for _, ts := range timestamps {
		t := time.Unix(ts, 0).UTC()
		formatted := t.Format("2006-01-02-15-04")
		fmt.Fprintf(w, "- %s: %d\n", formatted, stats[ts].NumMsgs)
	}
}

func printLogs(w io.Writer, logs []LogMsg) {
	for _, msg := range logs {
		fmt.Fprintf(w, "- %s", msg.Time.Format("2006-01-02T15:04:05.000000000Z07:00"))
		if msg.DecreasedTimestamp {
			fmt.Fprintf(w, ",T")
		} else {
			fmt.Fprintf(w, ",F")
		}

		fmt.Fprintf(w, ",%s", msg.LogFilename)
		fmt.Fprintf(w, ",%.6d", msg.LogLinenumber)
		fmt.Fprintf(w, ",%.6d", msg.CombinedLinenumber)
		fmt.Fprintf(w, ",%s", logLevelToStr(msg.Level))
		fmt.Fprintf(w, ",%s", msg.Msg)

		ctxData, _ := json.Marshal(msg.Context)
		fmt.Fprintf(w, "\n")
		fmt.Fprintf(w, "  context: %s", string(ctxData))

		fmt.Fprintf(w, "\n")
		fmt.Fprintf(w, "  orig: %s", msg.OrigLine)

		fmt.Fprintf(w, "\n")
	}
}

func logLevelToStr(logLevel LogLevel) string {
	switch logLevel {
	case LogLevelUnknown:
		return "----"
	case LogLevelDebug:
		return "debg"
	case LogLevelInfo:
		return "info"
	case LogLevelWarn:
		return "warn"
	case LogLevelError:
		return "erro"
	default:
		return "????"
	}
}