Debian Codegraph @

core/core_test.go

raw
1 package core
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "os"
8 "os/user"
9 "path/filepath"
10 "regexp"
11 "runtime"
12 "sort"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "github.com/dimonomid/clock"
19 "github.com/dimonomid/nerdlog/core/testutils"
20 "github.com/dimonomid/nerdlog/log"
21 "github.com/juju/errors"
22 "github.com/stretchr/testify/assert"
23 "gopkg.in/yaml.v2"
24 )
25
26 const coreTestOutputRoot = "/tmp/nerdlog_core_test_output"
27 const coreTestScenarioYamlFname = "test_scenario.yaml"
28
29 type CoreTestScenarioYaml struct {
30 Descr string `yaml:"descr"`
31
32 CurrentTime testutils.MyTime `yaml:"current_time"`
33
34 ManagerParams CoreTestScenarioManagerParams `yaml:"manager_params"`
35 TestSteps []CoreTestStep `yaml:"test_steps"`
36 }
37
38 // CoreTestScenarioManagerParams converts into LStreamsManagerParams.
39 type CoreTestScenarioManagerParams struct {
40 ConfigLogStreams map[string]CoreTestConfigLogStream `yaml:"config_log_streams"`
41
42 InitialLStreams string `yaml:"initial_lstreams"`
43 ClientID string `yaml:"client_id"`
44 }
45
46 // CoreTestConfigLogStream converts to ConfigLogStream (from config.go)
47 type CoreTestConfigLogStream struct {
48 LogFiles testutils.TestCaseLogfiles `yaml:"log_files"`
49
50 Options ConfigLogStreamOptions `yaml:"options"`
51 }
52
53 type CoreTestStep struct {
54 // Descr is a human-readable step description
55 Descr string `yaml:"descr"`
56
57 // Exactly one of the fields below must be non-nil
58
59 CheckState *CoreTestStepCheckState `yaml:"check_state"`
60
61 // If Query is non-nil, we'll send a query to the LStreamsManager.
62 Query *CoreTestStepQuery `yaml:"query"`
63 }
64
65 type CoreTestStepCheckState struct {
66 // WantByHostnameAndTransport is a map from the test hostname-and-transport
67 // string to the filename with the expected LStreamsManagerState.
68 //
69 // The hostname-and-transport string looks like this:
70 //
71 // - "localhost": for localhost, it's just this, since there is only one kind
72 // of transport
73 // - "127.0.0.1_ssh-lib": for non-localhost hostname without UseExternalSSH
74 // - "127.0.0.1_ssh-bin": for non-localhost hostname with UseExternalSSH
75 WantByHostnameAndTransport map[string]string `yaml:"want_by_hostname_and_transport"`
76 }
77
78 type CoreTestStepQuery struct {
79 Params CoreTestStepQueryParams `yaml:"params"`
80
81 // Want is a filename (relative to the test scenario dir) with the expected
82 // results.
83 Want string `yaml:"want"`
84 }
85
86 // CoreTestStepQueryParams converts into QueryLogsParams (from core.go).
87 type CoreTestStepQueryParams struct {
88 MaxNumLines int `yaml:"max_num_lines"`
89
90 From testutils.MyTime `yaml:"from"`
91 To testutils.MyTime `yaml:"to"`
92
93 Pattern string `yaml:"pattern"`
94
95 LoadEarlier bool `yaml:"load_earlier"`
96
97 RefreshIndex bool `yaml:"refresh_index"`
98 }
99
100 func (p *CoreTestStepQueryParams) RealParams() QueryLogsParams {
101 return QueryLogsParams{
102 MaxNumLines: p.MaxNumLines,
103 From: p.From.Time,
104 To: p.To.Time,
105 Query: p.Pattern,
106 LoadEarlier: p.LoadEarlier,
107 RefreshIndex: p.RefreshIndex,
108 }
109 }
110
111 func TestCoreScenarios(t *testing.T) {
112 _, filename, _, ok := runtime.Caller(0)
113 if !ok {
114 t.Fatal("unable to get caller info")
115 }
116
117 // Get directory of the current file
118 parentDir := filepath.Dir(filename)
119 testScenariosDir := filepath.Join(parentDir, "core_testdata", "test_cases_core")
120
121 repoRoot := filepath.Dir(filepath.Dir(filename))
122
123 if err := os.MkdirAll(coreTestOutputRoot, 0755); err != nil {
124 t.Fatalf("unable to create core test output root dir %s: %s", coreTestOutputRoot, err.Error())
125 }
126
127 testScenarioDirs, err := testutils.GetTestCaseDirs(testScenariosDir, coreTestScenarioYamlFname)
128 if err != nil {
129 panic(err)
130 }
131
132 for _, testName := range testScenarioDirs {
133 t.Run(testName, func(t *testing.T) {
134 tsCtx := &coreTestScenarioContext{
135 testName: testName,
136 testScenarioDir: filepath.Join(testScenariosDir, testName),
137 testOutputDir: filepath.Join(coreTestOutputRoot, testName),
138 repoRoot: repoRoot,
139 }
140
141 if err := runCoreTestScenario(t, tsCtx); err != nil {
142 t.Fatalf("running core test scenario %s: %s", testName, err.Error())
143 }
144 })
145 }
146 }
147
148 type coreTestScenarioContext struct {
149 testName string
150 testScenarioDir string
151 testOutputDir string
152 repoRoot string
153 }
154
155 func runCoreTestScenario(t *testing.T, tsCtx *coreTestScenarioContext) error {
156 testScenarioDescrFname := filepath.Join(tsCtx.testScenarioDir, coreTestScenarioYamlFname)
157
158 if err := os.MkdirAll(tsCtx.testOutputDir, 0755); err != nil {
159 return errors.Annotatef(err, "unable to create test output dir %s", tsCtx.testOutputDir)
160 }
161
162 data, err := os.ReadFile(testScenarioDescrFname)
163 if err != nil {
164 return errors.Annotatef(err, "reading yaml test case descriptor %s", testScenarioDescrFname)
165 }
166
167 var tc CoreTestScenarioYaml
168 if err := yaml.Unmarshal(data, &tc); err != nil {
169 return errors.Annotatef(err, "unmarshaling yaml from %s", testScenarioDescrFname)
170 }
171
172 if tc.CurrentTime.Time.IsZero() {
173 return errors.Annotatef(err, "current_time must not be zero in %s", testScenarioDescrFname)
174 }
175
176 clockMock := clock.NewMock()
177 clockMock.Set(tc.CurrentTime.Time)
178
179 manTH, err := newLStreamsManagerTestHelper(tc.ManagerParams, tsCtx, clockMock)
180 if err != nil {
181 return errors.Annotatef(err, "creating LStreamsManagerTestHelper")
182 }
183
184 fmt.Println("Waiting connection...")
185 manTH.WaitConnected()
186
187 isFirstQuery := true
188 for i, step := range tc.TestSteps {
189 stepSID := fmt.Sprintf("%.2d_%s", i+1, testutils.Slug(step.Descr))
190 stepOutputDir := filepath.Join(tsCtx.testOutputDir, "steps", stepSID)
191 if err := os.MkdirAll(stepOutputDir, 0755); err != nil {
192 return errors.Annotatef(err, "creating lstream dir %s", stepSID)
193 }
194
195 assertArgs := []interface{}{"test case %s", stepSID}
196
197 if checkState := step.CheckState; checkState != nil {
198 lsmStateStr := formatLSMState(manTH.GetLSMState())
199 err = os.WriteFile(filepath.Join(stepOutputDir, "got_logstreams_manager_state.txt"), []byte(lsmStateStr), 0644)
200 if err != nil {
201 return errors.Annotatef(err, "test step #%d: writing lsm state", i)
202 }
203
204 hostnameAndTransportKey := manTH.getHostnameAndTransportKey()
205 wantFilename := checkState.WantByHostnameAndTransport[hostnameAndTransportKey]
206
207 if wantFilename == "" {
208 return errors.Errorf("test step #%d: no WantByHostnameAndTransport for %q", i, hostnameAndTransportKey)
209 } else {
210 err = os.WriteFile(filepath.Join(stepOutputDir, "want_lsm_state_filename.txt"), []byte(wantFilename), 0644)
211 if err != nil {
212 return errors.Annotatef(err, "test step #%d: writing want_lsm_state_filename.txt", i)
213 }
214
215 wantLSMStateFilenameFull := filepath.Join(tsCtx.testScenarioDir, wantFilename)
216 wantLSMState, err := os.ReadFile(wantLSMStateFilenameFull)
217 if err != nil {
218 return errors.Annotatef(err, "test step #%d: reading wanted log resp %s", i, wantLSMStateFilenameFull)
219 }
220
221 assert.Equal(t, string(wantLSMState), lsmStateStr, assertArgs...)
222 }
223 } else if query := step.Query; query != nil {
224 // For reproducibility of the exact same debug output, refresh the index
225 // during the first query in a scenario.
226 if isFirstQuery {
227 query.Params.RefreshIndex = true
228 isFirstQuery = false
229 }
230
231 logResp, err := manTH.QueryLogs(query.Params)
232 if err != nil {
233 return errors.Annotatef(err, "test step #%d: querying logs %+v", i, query.Params)
234 }
235
236 logRespStr := formatLogResp(logResp)
237 err = os.WriteFile(filepath.Join(stepOutputDir, "got_log_resp.txt"), []byte(logRespStr), 0644)
238 if err != nil {
239 return errors.Annotatef(err, "test step #%d: writing log resp", i)
240 }
241
242 err = os.WriteFile(filepath.Join(stepOutputDir, "want_log_resp_filename.txt"), []byte(query.Want), 0644)
243 if err != nil {
244 return errors.Annotatef(err, "test step #%d: writing want_log_resp_filename.txt", i)
245 }
246
247 wantLogRespFilenameFull := filepath.Join(tsCtx.testScenarioDir, query.Want)
248 wantLogResp, err := os.ReadFile(wantLogRespFilenameFull)
249 if err != nil {
250 return errors.Annotatef(err, "test step #%d: reading wanted log resp %s", i, wantLogRespFilenameFull)
251 }
252
253 assert.Equal(t, string(wantLogResp), logRespStr, assertArgs...)
254 }
255 }
256
257 fmt.Println("Closing LStreamsManager...")
258 if err := manTH.CloseAndWait(); err != nil {
259 return errors.Trace(err)
260 }
261
262 return nil
263 }
264
265 type LStreamsManagerTestHelper struct {
266 manager *LStreamsManager
267 updatesCh chan LStreamsManagerUpdate
268 clock *clock.Mock
269
270 state LStreamsManagerTestHelperState
271 stateMtx sync.Mutex
272 }
273
274 type LStreamsManagerTestHelperState struct {
275 lsmState *LStreamsManagerState
276 pendingLogResps []*LogRespTotal
277 }
278
279 func newLStreamsManagerTestHelper(
280 params CoreTestScenarioManagerParams,
281 tsCtx *coreTestScenarioContext,
282 clockMock *clock.Mock,
283 ) (*LStreamsManagerTestHelper, error) {
284 updatesCh := make(chan LStreamsManagerUpdate, 100)
285
286 cfgLogStreams := make(ConfigLogStreams, len(params.ConfigLogStreams))
287 for lstreamName, testCfg := range params.ConfigLogStreams {
288 resolved, err := testutils.ResolveLogfiles(tsCtx.testScenarioDir, &testCfg.LogFiles)
289 if err != nil {
290 return nil, errors.Annotatef(err, "resolving logfiles")
291 }
292
293 testOutputLstreamDir := filepath.Join(tsCtx.testOutputDir, "lstreams", lstreamName)
294 if err := os.MkdirAll(testOutputLstreamDir, 0755); err != nil {
295 return nil, errors.Annotatef(err, "creating lstream dir %s", lstreamName)
296 }
297
298 provisioned, err := testutils.ProvisionLogFiles(
299 resolved,
300 testOutputLstreamDir,
301 tsCtx.repoRoot,
302 )
303 if err != nil {
304 return nil, errors.Annotatef(err, "provisioning logfiles")
305 }
306
307 options := testCfg.Options
308 for _, envVar := range provisioned.ExtraEnv {
309 options.ShellInit = append(options.ShellInit, fmt.Sprintf("export %s", envVar))
310 }
311
312 cfgLogStreams[lstreamName] = ConfigLogStream{
313 Hostname: getCoreTestHostname(),
314 LogFiles: []string{
315 provisioned.LogfileLast,
316 provisioned.LogfilePrev,
317 },
318 Options: options,
319 }
320 }
321
322 manParams := LStreamsManagerParams{
323 ConfigLogStreams: cfgLogStreams,
324 Logger: log.NewLogger(log.Verbose1).WithStdout(true),
325 InitialLStreams: params.InitialLStreams,
326 ClientID: params.ClientID,
327 UpdatesCh: updatesCh,
328 Clock: clockMock,
329
330 InitialUseExternalSSH: os.Getenv("NERDLOG_CORE_TEST_TRANSPORT_SSH_BIN") != "",
331 }
332
333 fmt.Println("Creating LStreamsManager...")
334 manager := NewLStreamsManager(manParams)
335
336 manTH := &LStreamsManagerTestHelper{
337 manager: manager,
338 updatesCh: updatesCh,
339 clock: clockMock,
340 }
341
342 go manTH.run()
343
344 return manTH, nil
345 }
346
347 // getCoreTestHostname finds out the hostname: normally we use just
348 // `localhost`, which means we'll use ShellTransportLocal, but it can be
349 // overridden with the NERDLOG_CORE_TEST_HOSTNAME env var. Keep in mind that
350 // only `localhost` bypasses ssh; so e.g. "127.0.0.1" will use
351 // ShellTransportSSH, and we can take advantage of that to cover the ssh
352 // transport in tests. Obviously, for that the ssh server needs to be running
353 // locally.
354 func getCoreTestHostname() string {
355 hostname := os.Getenv("NERDLOG_CORE_TEST_HOSTNAME")
356 if hostname == "" {
357 hostname = "localhost"
358 }
359
360 return hostname
361 }
362
363 func (th *LStreamsManagerTestHelper) getHostnameAndTransportKey() string {
364 testHostname := getCoreTestHostname()
365 if testHostname == "localhost" {
366 return testHostname
367 }
368
369 useExternalSSH := th.manager.useExternalSSH
370 transportStr := "ssh-lib"
371 if useExternalSSH {
372 transportStr = "ssh-bin"
373 }
374
375 return fmt.Sprintf("%s_%s", testHostname, transportStr)
376 }
377
378 func (th *LStreamsManagerTestHelper) run() {
379 for upd := range th.updatesCh {
380 th.applyUpdate(upd)
381 }
382 }
383
384 func (th *LStreamsManagerTestHelper) applyUpdate(upd LStreamsManagerUpdate) {
385 //d, _ := json.Marshal(upd)
386 //fmt.Printf(" UPD: %s\n", string(d))
387
388 th.stateMtx.Lock()
389 defer th.stateMtx.Unlock()
390
391 if upd.State != nil {
392 th.state.lsmState = upd.State
393 } else if upd.LogResp != nil {
394 th.state.pendingLogResps = append(th.state.pendingLogResps, upd.LogResp)
395 }
396 }
397
398 func (th *LStreamsManagerTestHelper) isConnected() bool {
399 th.stateMtx.Lock()
400 defer th.stateMtx.Unlock()
401
402 return th.state.lsmState != nil && th.state.lsmState.Connected
403 }
404
405 func (th *LStreamsManagerTestHelper) nextLogResp() *LogRespTotal {
406 th.stateMtx.Lock()
407 defer th.stateMtx.Unlock()
408
409 if len(th.state.pendingLogResps) == 0 {
410 return nil
411 }
412
413 ret := th.state.pendingLogResps[0]
414 th.state.pendingLogResps = th.state.pendingLogResps[1:]
415
416 return ret
417 }
418
419 func (th *LStreamsManagerTestHelper) WaitConnected() {
420 for {
421 if th.isConnected() {
422 return
423 }
424
425 // TODO: We could implement subscribing to state updates, but for now just polling.
426 time.Sleep(100 * time.Millisecond)
427 }
428 }
429
430 func (th *LStreamsManagerTestHelper) QueryLogs(params CoreTestStepQueryParams) (*LogRespTotal, error) {
431 // Sanity check that there is no existing pending log resp
432 existing := th.nextLogResp()
433 if existing != nil {
434 return existing, errors.Errorf("there was existing pending log resp")
435 }
436
437 th.manager.QueryLogs(params.RealParams())
438
439 return th.WaitNextLogResp()
440 }
441
442 func (th *LStreamsManagerTestHelper) GetLSMState() *LStreamsManagerState {
443 return th.state.lsmState
444 }
445
446 func (th *LStreamsManagerTestHelper) WaitNextLogResp() (*LogRespTotal, error) {
447 start := time.Now()
448
449 for {
450 ret := th.nextLogResp()
451 if ret != nil {
452 return ret, nil
453 }
454
455 if time.Since(start) > 5*time.Second {
456 return nil, errors.Errorf("timed out waiting for log resp")
457 }
458
459 // TODO: We could implement subscribing to state updates, but for now just polling.
460 time.Sleep(100 * time.Millisecond)
461 }
462 }
463
464 func (th *LStreamsManagerTestHelper) CloseAndWait() error {
465 th.manager.Close()
466
467 closedCh := make(chan struct{})
468 go func() {
469 th.manager.Wait()
470 close(closedCh)
471 }()
472
473 select {
474 case <-closedCh:
475 // All good
476 return nil
477 case <-time.After(5 * time.Second):
478 return errors.Errorf("timed out waiting for LStreamsManager to close")
479 }
480 }
481
482 func formatLogResp(logResp *LogRespTotal) string {
483 var sb strings.Builder
484
485 sb.WriteString(fmt.Sprintf("NumMsgsTotal: %v\n", logResp.NumMsgsTotal))
486 sb.WriteString(fmt.Sprintf("LoadedEarlier: %v\n", logResp.LoadedEarlier))
487 sb.WriteString(fmt.Sprintf("Num errors: %v\n", len(logResp.Errs)))
488 for _, err := range logResp.Errs {
489 sb.WriteString(fmt.Sprintf("- %s", err.Error()))
490 }
491
492 sb.WriteString("\n")
493 sb.WriteString(fmt.Sprintf("Num MinuteStats: %v\n", len(logResp.MinuteStats)))
494 printMinuteStats(&sb, logResp.MinuteStats)
495
496 sb.WriteString("\n")
497 sb.WriteString(fmt.Sprintf("Num Logs: %v\n", len(logResp.Logs)))
498 printLogs(&sb, logResp.Logs)
499
500 sb.WriteString("\n")
501 debugInfoData, _ := json.MarshalIndent(logResp.DebugInfo, "", " ")
502 sb.WriteString(fmt.Sprintf("DebugInfo:\n%s", debugInfoData))
503
504 return sb.String()
505 }
506
507 func formatLSMState(lsmState *LStreamsManagerState) string {
508 data, _ := json.MarshalIndent(lsmState, "", " ")
509 str := string(data)
510
511 // We also need to replace the OS username in the payload with a static
512 // placeholder, since it can be different.
513 str = maskOSUser(str)
514
515 return str
516 }
517
518 // maskOSUser returns a string with all occurrences of the current OS user
519 // replaced with "__TEST_OS_USER__".
520 func maskOSUser(s string) string {
521 u, err := user.Current()
522 if err != nil {
523 // Can't determine the user, return the input unchanged
524 return s
525 }
526
527 re := regexp.MustCompile(`\b` + regexp.QuoteMeta(u.Username) + `\b`)
528 return re.ReplaceAllString(s, "__TEST_OS_USER__")
529 }
530
531 func printMinuteStats(w io.Writer, stats map[int64]MinuteStatsItem) {
532 // Extract and sort timestamps for consistent output
533 timestamps := make([]int64, 0, len(stats))
534 for ts := range stats {
535 timestamps = append(timestamps, ts)
536 }
537 sort.Slice(timestamps, func(i, j int) bool {
538 return timestamps[i] < timestamps[j]
539 })
540
541 // Print each item
542 for _, ts := range timestamps {
543 t := time.Unix(ts, 0).UTC()
544 formatted := t.Format("2006-01-02-15-04")
545 fmt.Fprintf(w, "- %s: %d\n", formatted, stats[ts].NumMsgs)
546 }
547 }
548
549 func printLogs(w io.Writer, logs []LogMsg) {
550 for _, msg := range logs {
551 fmt.Fprintf(w, "- %s", msg.Time.Format("2006-01-02T15:04:05.000000000Z07:00"))
552 if msg.DecreasedTimestamp {
553 fmt.Fprintf(w, ",T")
554 } else {
555 fmt.Fprintf(w, ",F")
556 }
557
558 fmt.Fprintf(w, ",%s", msg.LogFilename)
559 fmt.Fprintf(w, ",%.6d", msg.LogLinenumber)
560 fmt.Fprintf(w, ",%.6d", msg.CombinedLinenumber)
561 fmt.Fprintf(w, ",%s", logLevelToStr(msg.Level))
562 fmt.Fprintf(w, ",%s", msg.Msg)
563
564 ctxData, _ := json.Marshal(msg.Context)
565 fmt.Fprintf(w, "\n")
566 fmt.Fprintf(w, " context: %s", string(ctxData))
567
568 fmt.Fprintf(w, "\n")
569 fmt.Fprintf(w, " orig: %s", msg.OrigLine)
570
571 fmt.Fprintf(w, "\n")
572 }
573 }
574
575 func logLevelToStr(logLevel LogLevel) string {
576 switch logLevel {
577 case LogLevelUnknown:
578 return "----"
579 case LogLevelDebug:
580 return "debg"
581 case LogLevelInfo:
582 return "info"
583 case LogLevelWarn:
584 return "warn"
585 case LogLevelError:
586 return "erro"
587 default:
588 return "????"
589 }
590 }