Skip to content

Commit 0bb2dbb

Browse files
mergify[bot]michel-latermanycombinator
authored
Fix configFromUnit test, add logging for e2e tests (#5396) (#5405)
* Fix configFromUnit test, add logging for e2e tests * Fix linter * Fix data race * linter suggestions * Apply suggestions from code review --------- (cherry picked from commit 35012a1) Co-authored-by: Michel Laterman <[email protected]> Co-authored-by: Shaunak Kashyap <[email protected]>
1 parent b35773f commit 0bb2dbb

File tree

4 files changed

+62
-49
lines changed

4 files changed

+62
-49
lines changed

internal/pkg/server/agent.go

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -282,50 +282,48 @@ func (a *Agent) unitModified(ctx context.Context, unit *client.Unit) error {
282282
// not our input unit; would have been marked failed in unitAdded; do nothing
283283
return nil
284284
}
285-
if exp.State == client.UnitStateHealthy {
285+
switch exp.State {
286+
case client.UnitStateHealthy:
286287
if a.outputUnit == nil {
287288
// still no output unit; would have been marked starting already; do nothing
288289
return nil
289290
}
290-
291291
// configuration modified (should still be running)
292292
return a.reconfigure(ctx)
293-
} else if exp.State == client.UnitStateStopped {
293+
case client.UnitStateStopped:
294294
// unit should be stopped
295295
a.stop()
296296
return nil
297+
default:
298+
return fmt.Errorf("unknown unit state %v", exp.State)
297299
}
298-
return fmt.Errorf("unknown unit state %v", exp.State)
299300
}
300301
if unit.Type() == client.UnitTypeOutput {
301302
if a.outputUnit != unit {
302303
// not our output unit; would have been marked failed in unitAdded; do nothing
303304
return nil
304305
}
305-
if exp.State == client.UnitStateHealthy {
306+
switch exp.State {
307+
case client.UnitStateHealthy:
306308
if a.inputUnit == nil {
307309
// still no input unit; would have been marked starting already; do nothing
308310
return nil
309311
}
310-
311312
// configuration modified (should still be running)
312313
return a.reconfigure(ctx)
313-
} else if exp.State == client.UnitStateStopped {
314+
case client.UnitStateStopped:
314315
// unit should be stopped
315316
a.stop()
316317
return nil
318+
default:
319+
return fmt.Errorf("unknown unit state %v", exp.State)
317320
}
318-
return fmt.Errorf("unknown unit state %v", exp.State)
319321
}
320322
return fmt.Errorf("unknown unit type %v", unit.Type())
321323
}
322324

323325
func (a *Agent) unitRemoved(unit *client.Unit) {
324-
stop := false
325326
if a.inputUnit == unit || a.outputUnit == unit {
326-
stop = true
327-
}
328-
if stop {
329327
a.stop()
330328
}
331329
if a.inputUnit == unit {
@@ -726,8 +724,7 @@ func (a *Agent) esOutputCheck(ctx context.Context, cfg map[string]interface{}) e
726724
func (a *Agent) esOutputCheckLoop(ctx context.Context, delay time.Duration, cfg map[string]interface{}) {
727725
for {
728726
if err := sleep.WithContext(ctx, delay); err != nil {
729-
zerolog.Ctx(ctx).Debug().Msg("Async output check context cancelled")
730-
return
727+
return // context cancelled
731728
}
732729
err := a.esOutputCheck(ctx, cfg)
733730
if err == nil {

internal/pkg/server/agent_test.go

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,17 @@ import (
1111
"testing"
1212
"time"
1313

14+
"github.com/stretchr/testify/assert"
15+
"github.com/stretchr/testify/mock"
16+
"github.com/stretchr/testify/require"
17+
"google.golang.org/protobuf/types/known/structpb"
18+
1419
"github.com/elastic/elastic-agent-client/v7/pkg/client"
1520
"github.com/elastic/elastic-agent-client/v7/pkg/proto"
1621
"github.com/elastic/fleet-server/v7/internal/pkg/build"
1722
testlog "github.com/elastic/fleet-server/v7/internal/pkg/testing/log"
1823
"github.com/elastic/fleet-server/v7/version"
1924
"github.com/elastic/go-ucfg"
20-
"github.com/stretchr/testify/assert"
21-
"github.com/stretchr/testify/mock"
22-
"github.com/stretchr/testify/require"
23-
"google.golang.org/protobuf/types/known/structpb"
2425
)
2526

2627
func TestCLIOverrides(t *testing.T) {
@@ -88,7 +89,7 @@ func TestCLIOverrides(t *testing.T) {
8889
agent: clientMock,
8990
}
9091

91-
generatedCfg, err := agent.configFromUnits(context.Background())
92+
generatedCfg, err := agent.configFromUnits(t.Context())
9293
require.NoError(t, err)
9394
require.Equal(t, httpEnabledExpected, generatedCfg.HTTP.Enabled)
9495
require.Equal(t, httpHostExpected, generatedCfg.HTTP.Host)
@@ -108,29 +109,29 @@ func (c *mockClientV2) RegisterOptionalDiagnosticHook(paramTag string, name stri
108109

109110
func (c *mockClientV2) Start(ctx context.Context) error {
110111
args := c.Called()
111-
return args.Get(0).(error)
112+
return args.Get(0).(error) //nolint:errcheck // testing mock
112113
}
113114

114115
func (c *mockClientV2) Stop() {}
115116

116117
func (c *mockClientV2) UnitChanges() <-chan client.UnitChanged {
117118
args := c.Called()
118-
return args.Get(0).(<-chan client.UnitChanged)
119+
return args.Get(0).(<-chan client.UnitChanged) //nolint:errcheck // testing mock
119120
}
120121

121122
func (c *mockClientV2) Errors() <-chan error {
122123
args := c.Called()
123-
return args.Get(0).(<-chan error)
124+
return args.Get(0).(<-chan error) //nolint:errcheck // testing mock
124125
}
125126

126127
func (c *mockClientV2) Artifacts() client.ArtifactsClient {
127128
args := c.Called()
128-
return args.Get(0).(client.ArtifactsClient)
129+
return args.Get(0).(client.ArtifactsClient) //nolint:errcheck // testing mock
129130
}
130131

131132
func (c *mockClientV2) AgentInfo() *client.AgentInfo {
132133
args := c.Called()
133-
return args.Get(0).(*client.AgentInfo)
134+
return args.Get(0).(*client.AgentInfo) //nolint:errcheck // testing mock
134135
}
135136

136137
type mockClientUnit struct {
@@ -140,12 +141,12 @@ type mockClientUnit struct {
140141
func (u *mockClientUnit) Expected() client.Expected {
141142
args := u.Called()
142143

143-
return args.Get(0).(client.Expected)
144+
return args.Get(0).(client.Expected) //nolint:errcheck // testing mock
144145
}
145146

146147
func (u *mockClientUnit) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error {
147148
args := u.Called()
148-
return args.Get(0).(error)
149+
return args.Get(0).(error) //nolint:errcheck // testing mock
149150
}
150151

151152
func Test_Agent_configFromUnits(t *testing.T) {
@@ -194,7 +195,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
194195
outputUnit: mockOutClient,
195196
}
196197

197-
cfg, err := a.configFromUnits(context.Background())
198+
cfg, err := a.configFromUnits(t.Context())
198199
require.NoError(t, err)
199200
require.Len(t, cfg.Inputs, 1)
200201
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -234,7 +235,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
234235
outputUnit: mockOutClient,
235236
}
236237

237-
cfg, err := a.configFromUnits(context.Background())
238+
cfg, err := a.configFromUnits(t.Context())
238239
require.NoError(t, err)
239240
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
240241
require.Len(t, cfg.Output.Elasticsearch.Hosts, 2)
@@ -295,7 +296,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
295296
outputUnit: mockOutClient,
296297
}
297298

298-
cfg, err := a.configFromUnits(context.Background())
299+
cfg, err := a.configFromUnits(t.Context())
299300
require.NoError(t, err)
300301
require.Len(t, cfg.Inputs, 1)
301302
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -375,7 +376,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
375376
outputUnit: mockOutClient,
376377
}
377378

378-
cfg, err := a.configFromUnits(context.Background())
379+
cfg, err := a.configFromUnits(t.Context())
379380
require.NoError(t, err)
380381
require.Len(t, cfg.Inputs, 1)
381382
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -439,7 +440,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
439440
outputUnit: mockOutClient,
440441
}
441442

442-
cfg, err := a.configFromUnits(context.Background())
443+
cfg, err := a.configFromUnits(t.Context())
443444
require.NoError(t, err)
444445
require.Len(t, cfg.Inputs, 1)
445446
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -518,7 +519,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
518519
outputUnit: mockOutClient,
519520
}
520521

521-
cfg, err := a.configFromUnits(context.Background())
522+
cfg, err := a.configFromUnits(t.Context())
522523
require.NoError(t, err)
523524
require.Len(t, cfg.Inputs, 1)
524525
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -571,7 +572,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
571572
outputUnit: mockOutClient,
572573
}
573574

574-
cfg, err := a.configFromUnits(context.Background())
575+
cfg, err := a.configFromUnits(t.Context())
575576
require.NoError(t, err)
576577
require.Len(t, cfg.Inputs, 1)
577578
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -625,7 +626,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
625626
outputUnit: mockOutClient,
626627
}
627628

628-
cfg, err := a.configFromUnits(context.Background())
629+
cfg, err := a.configFromUnits(t.Context())
629630
require.NoError(t, err)
630631
require.Len(t, cfg.Inputs, 1)
631632
assert.Equal(t, "fleet-server", cfg.Inputs[0].Type)
@@ -684,7 +685,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
684685
},
685686
}
686687

687-
ctx := testlog.SetLogger(t).WithContext(context.Background())
688+
ctx := testlog.SetLogger(t).WithContext(t.Context())
688689
cfg, err := a.configFromUnits(ctx)
689690
require.NoError(t, err)
690691
assert.Equal(t, "test-token", cfg.Output.Elasticsearch.ServiceToken)
@@ -734,7 +735,7 @@ func Test_Agent_configFromUnits(t *testing.T) {
734735
},
735736
}
736737

737-
ctx := testlog.SetLogger(t).WithContext(context.Background())
738+
ctx := testlog.SetLogger(t).WithContext(t.Context())
738739
cfg, err := a.configFromUnits(ctx)
739740
require.NoError(t, err)
740741
assert.Equal(t, "test-token", cfg.Output.Elasticsearch.ServiceToken)
@@ -839,7 +840,7 @@ func TestInjectMissingOutputAttributes(t *testing.T) {
839840
}
840841
for _, tc := range tests {
841842
t.Run(tc.name, func(t *testing.T) {
842-
injectMissingOutputAttributes(context.Background(), tc.input, bootstrap)
843+
injectMissingOutputAttributes(t.Context(), tc.input, bootstrap)
843844
assert.Equal(t, len(tc.expect), len(tc.input), "expected map sizes don't match")
844845
assert.Equal(t, tc.expect, tc.input)
845846
})
@@ -914,7 +915,7 @@ func TestInjectMissingOutputAttributes(t *testing.T) {
914915

915916
for _, tc := range sslTests {
916917
t.Run(tc.name, func(t *testing.T) {
917-
injectMissingOutputAttributes(context.Background(), tc.input, bootstrapVerifyNone)
918+
injectMissingOutputAttributes(t.Context(), tc.input, bootstrapVerifyNone)
918919
assert.Equal(t, len(tc.expect), len(tc.input), "expected map sizes don't match")
919920
assert.Equal(t, tc.expect, tc.input)
920921
})
@@ -928,7 +929,7 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) {
928929
chReconfigure: make(chan struct{}, 1),
929930
}
930931

931-
ctx, cancel := context.WithCancel(context.Background())
932+
ctx, cancel := context.WithCancel(t.Context())
932933
cancel()
933934
a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{})
934935
assert.Empty(t, a.chReconfigure)
@@ -948,7 +949,7 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) {
948949
},
949950
chReconfigure: make(chan struct{}, 1),
950951
}
951-
ctx, cancel := context.WithCancel(context.Background())
952+
ctx, cancel := context.WithCancel(t.Context())
952953
defer cancel()
953954
a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{
954955
"service_token": "test-token",
@@ -977,7 +978,7 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) {
977978
},
978979
chReconfigure: make(chan struct{}, 1),
979980
}
980-
ctx, cancel := context.WithCancel(context.Background())
981+
ctx, cancel := context.WithCancel(t.Context())
981982
defer cancel()
982983
a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{
983984
"service_token": "test-token",

internal/pkg/ver/check.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@ import (
1313
"strconv"
1414
"strings"
1515

16-
esh "github.com/elastic/fleet-server/v7/internal/pkg/es"
1716
"github.com/rs/zerolog"
1817

18+
esh "github.com/elastic/fleet-server/v7/internal/pkg/es"
19+
1920
"github.com/hashicorp/go-version"
2021

2122
"github.com/elastic/go-elasticsearch/v8"
@@ -30,15 +31,24 @@ var (
3031
// CheckCompatiblility will check the remote Elasticsearch version retrieved by the Elasticsearch client with the passed fleet version.
3132
// Versions are compatible when Elasticsearch's version is greater then or equal to fleet-server's version
3233
func CheckCompatibility(ctx context.Context, esCli *elasticsearch.Client, fleetVersion string) (string, error) {
33-
zerolog.Ctx(ctx).Debug().Str("fleet_version", fleetVersion).Msg("check version compatibility with elasticsearch")
34+
// Version checks may run concurrently with other operations
35+
// This can cause some flakiness with tests so we need to get the logger from the context before its cancelled
36+
var logger *zerolog.Logger
37+
select {
38+
case <-ctx.Done():
39+
return "", ctx.Err()
40+
default:
41+
logger = zerolog.Ctx(ctx)
42+
}
43+
logger.Debug().Str("fleet_version", fleetVersion).Msg("check version compatibility with elasticsearch")
3444

3545
esVersion, err := esh.FetchESVersion(ctx, esCli)
3646

3747
if err != nil {
38-
zerolog.Ctx(ctx).Error().Err(err).Msg("failed to fetch elasticsearch version")
48+
logger.Error().Err(err).Msg("failed to fetch elasticsearch version")
3949
return "", err
4050
}
41-
zerolog.Ctx(ctx).Debug().Str("elasticsearch_version", esVersion).Msg("fetched elasticsearch version")
51+
logger.Debug().Str("elasticsearch_version", esVersion).Msg("fetched elasticsearch version")
4252

4353
return esVersion, checkCompatibility(ctx, fleetVersion, esVersion)
4454
}

testing/e2e/scaffold/scaffold.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -244,20 +244,25 @@ func (s *Scaffold) AgentIsOnline(ctx context.Context, id string) {
244244
req.Header.Set("kbn-xsrf", "e2e-setup")
245245

246246
resp, err := s.Client.Do(req)
247-
s.Require().NoError(err)
248-
defer resp.Body.Close()
247+
s.Require().NoError(err, "kibana agent request failure")
249248
if resp.StatusCode != http.StatusOK {
250249
timer.Reset(time.Second)
250+
resp.Body.Close()
251251
continue
252252
}
253253

254+
p, err := io.ReadAll(resp.Body)
255+
s.Require().NoError(err, "unable to read kibana agent response")
256+
resp.Body.Close()
257+
254258
var obj struct {
255259
Item struct {
256260
Status string `json:"status"`
257261
} `json:"item"`
258262
}
259-
err = json.NewDecoder(resp.Body).Decode(&obj)
260-
s.Require().NoError(err)
263+
s.T().Logf("Kibana agent response: %s", string(p))
264+
err = json.Unmarshal(p, &obj)
265+
s.Require().NoError(err, "unmarshal failure")
261266
if obj.Item.Status == "online" {
262267
return
263268
}

0 commit comments

Comments
 (0)