|
18 | 18 | package beater |
19 | 19 |
|
20 | 20 | import ( |
| 21 | + "errors" |
21 | 22 | "testing" |
22 | 23 | "time" |
23 | 24 |
|
| 25 | + "github.com/stretchr/testify/require" |
| 26 | + |
| 27 | + "github.com/elastic/beats/v7/filebeat/fileset" |
| 28 | + "github.com/elastic/beats/v7/libbeat/beat" |
| 29 | + "github.com/elastic/beats/v7/libbeat/beatmonitoring" |
| 30 | + "github.com/elastic/beats/v7/libbeat/management" |
24 | 31 | "github.com/elastic/elastic-agent-libs/logp" |
25 | 32 | ) |
26 | 33 |
|
| 34 | +// TestRunClosesRunReadyOnPreInitFailure guards against the regression in |
| 35 | +// commit 00068f7 where the defer fb.runReady.Close() was placed after the |
| 36 | +// PreInit call, leaving runReady unclosed when PreInit fails. An unclosed |
| 37 | +// runReady causes StopWithContext to wait the full five-second timeout. |
| 38 | +func TestRunClosesRunReadyOnPreInitFailure(t *testing.T) { |
| 39 | + preInitErr := errors.New("preinit failed") |
| 40 | + fb := &Filebeat{ |
| 41 | + done: make(chan struct{}), |
| 42 | + runReady: &closeOnce{ch: make(chan struct{})}, |
| 43 | + logger: logp.NewNopLogger(), |
| 44 | + moduleRegistry: new(fileset.ModuleRegistry), |
| 45 | + } |
| 46 | + b := &beat.Beat{ |
| 47 | + Info: beat.Info{Logger: logp.NewNopLogger()}, |
| 48 | + Manager: &preinitFailManager{err: preInitErr}, |
| 49 | + Monitoring: beatmonitoring.NewMonitoring(), |
| 50 | + } |
| 51 | + |
| 52 | + err := fb.Run(b) |
| 53 | + require.ErrorIs(t, err, preInitErr) |
| 54 | + |
| 55 | + select { |
| 56 | + case <-fb.runReady.ch: |
| 57 | + // runReady was closed — StopWithContext will not block |
| 58 | + default: |
| 59 | + t.Fatal("runReady was not closed after PreInit failure; StopWithContext would wait five seconds") |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// preinitFailManager is a management.Manager stub whose PreInit returns an |
| 64 | +// error. Only the methods called by Run before PreInit are implemented; any |
| 65 | +// other call panics, catching unexpected code paths during the test. |
| 66 | +type preinitFailManager struct { |
| 67 | + management.Manager // zero-valued; panics on any unimplemented method |
| 68 | + err error |
| 69 | +} |
| 70 | + |
| 71 | +func (m *preinitFailManager) Enabled() bool { return true } |
| 72 | +func (m *preinitFailManager) PreInit() error { return m.err } |
| 73 | +func (m *preinitFailManager) RegisterDiagnosticHook(_, _, _, _ string, _ management.DiagnosticHook) { |
| 74 | +} |
| 75 | + |
27 | 76 | // TestStopWaitsForRunReady proves that Stop does not close the done channel |
28 | 77 | // until Run has closed runReady (i.e., reached waitFinished.Wait). |
29 | 78 | // This guards against a race where the OTel collector calls Shutdown before |
|
0 commit comments