-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathpackage_version_test.go
375 lines (315 loc) · 11.6 KB
/
package_version_test.go
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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
//go:build integration
package integration
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v2"
"github.com/elastic/elastic-agent/pkg/control/v2/client"
atesting "github.com/elastic/elastic-agent/pkg/testing"
"github.com/elastic/elastic-agent/pkg/testing/define"
"github.com/elastic/elastic-agent/pkg/testing/tools/fleettools"
"github.com/elastic/elastic-agent/pkg/testing/tools/testcontext"
"github.com/elastic/elastic-agent/version"
)
func TestPackageVersion(t *testing.T) {
define.Require(t, define.Requirements{
Group: Default,
Local: true,
})
f, err := define.NewFixtureFromLocalBuild(t, define.Version())
require.NoError(t, err)
ctx, cancel := testcontext.WithDeadline(t, context.Background(), time.Now().Add(10*time.Minute))
defer cancel()
err = f.Prepare(ctx, fakeComponent)
require.NoError(t, err)
t.Run("check package version without the agent running", testAgentPackageVersion(ctx, f, true))
// run the agent and check the daemon version as well
t.Run("check package version while the agent is running", testVersionWithRunningAgent(ctx, f))
// Destructive/mutating tests ahead! If you need to do a normal test on a healthy installation of agent, put it before the tests below
// change the version in the version file and verify that the agent returns the new value
t.Run("check package version after updating file", testVersionAfterUpdatingFile(ctx, f))
// remove the pkg version file and check that we return the default beats version
t.Run("remove package versions file and test version again", testAfterRemovingPkgVersionFiles(ctx, f))
}
func TestComponentBuildHashInDiagnostics(t *testing.T) {
info := define.Require(t, define.Requirements{
Group: Fleet,
Stack: &define.Stack{},
Local: false, // requires Agent installation
Sudo: true, // requires Agent installation
})
ctx := context.Background()
f, err := define.NewFixtureFromLocalBuild(t, define.Version())
require.NoError(t, err, "could not create new fixture")
err = f.Prepare(ctx)
require.NoError(t, err, "could not prepare fixture")
enrollParams, err := fleettools.NewEnrollParams(ctx, info.KibanaClient)
require.NoError(t, err, "failed preparing Agent enrollment")
t.Log("Installing Elastic Agent...")
installOpts := atesting.InstallOpts{
NonInteractive: true,
Force: true,
EnrollOpts: atesting.EnrollOpts{
URL: enrollParams.FleetURL,
EnrollmentToken: enrollParams.EnrollmentToken,
},
}
output, err := f.Install(ctx, &installOpts)
require.NoError(t, err,
"failed to install start agent [output: %s]", string(output))
stateBuff := bytes.Buffer{}
var status atesting.AgentStatusOutput
allHealthy := func() bool {
stateBuff.Reset()
status, err = f.ExecStatus(ctx)
if err != nil {
stateBuff.WriteString(fmt.Sprintf("failed to get agent status: %v",
err))
return false
}
if client.State(status.State) != client.Healthy {
stateBuff.WriteString(fmt.Sprintf(
"agent isn't healthy: %s-%s",
client.State(status.State), status.Message))
return false
}
if len(status.Components) == 0 {
stateBuff.WriteString(fmt.Sprintf(
"healthy but without components: agent status: %s-%s",
client.State(status.State), status.Message))
return false
}
// the agent might be healthy but waiting its first configuration,
// in that case, there would be no components yet. Therefore, ensure
// the agent received the policy with components before proceeding with
// the test.
for _, c := range status.Components {
bs, err := json.MarshalIndent(status, "", " ")
if err != nil {
stateBuff.WriteString(fmt.Sprintf(
"%s not healthy, could not marshal status outptu: %v",
c.Name, err))
return false
}
state := client.State(c.State)
if state != client.Healthy {
stateBuff.WriteString(fmt.Sprintf(
"%s not health, agent status output: %s",
c.Name, bs))
return false
}
// there is a rare a race condition unlike to happen on a
// production scenario where the component is healthy but the
// version info delays to update. As the Status command and the
// diagnostics fetch this information in the same way, it guarantees
// the version info is up-to-date before proceeding with the test.
if c.VersionInfo.Meta.Commit == "" {
stateBuff.WriteString(fmt.Sprintf(
"%s health, but no versionInfo. agent status output: %s",
c.Name, bs))
return false
}
}
return true
}
require.Eventuallyf(t,
allHealthy,
5*time.Minute, 10*time.Second,
"agent never became healthy. Last status: %v", &stateBuff)
defer func() {
if !t.Failed() {
return
}
t.Logf("test failed: last status output: %#v", status)
}()
agentbeat := "agentbeat"
if runtime.GOOS == "windows" {
agentbeat += ".exe"
}
wd := f.WorkDir()
glob := filepath.Join(wd, "data", "elastic-agent-*", "components", agentbeat)
compPaths, err := filepath.Glob(glob)
require.NoErrorf(t, err, "failed to glob agentbeat path pattern %q", glob)
require.Lenf(t, compPaths, 1,
"glob pattern \"%s\": found %d paths to agentbeat, can only have 1",
glob, len(compPaths))
cmdVer := exec.Command(compPaths[0], "filebeat", "version")
output, err = cmdVer.CombinedOutput()
require.NoError(t, err, "failed to get filebeat version")
outStr := string(output)
// version output example:
// filebeat version 8.14.0 (arm64), libbeat 8.14.0 [ab27a657e4f15976c181cf44c529bba6159f2c64 built 2024-04-17 18:13:16 +0000 UTC]
t.Log("parsing commit hash from filebeat version: ", outStr)
splits := strings.Split(outStr, "[")
require.Lenf(t, splits, 2,
"expected beats output version to be split into 2, it was split into %q",
strings.Join(splits, "|"))
splits = strings.Split(splits[1], " built")
require.Lenf(t, splits, 2,
"expected split of beats output version to be split into 2, it was split into %q",
strings.Join(splits, "|"))
wantBuildHash := splits[0]
diagZip, err := f.ExecDiagnostics(ctx)
require.NoError(t, err, "failed collecting diagnostics")
diag := t.TempDir()
extractZipArchive(t, diagZip, diag)
// if the test fails, the diagnostics used is useful for debugging.
defer func() {
if !t.Failed() {
return
}
t.Logf("the test failed: trying to save the diagnostics used on the test")
diagDir, err := f.DiagnosticsDir()
if err != nil {
t.Logf("could not get diagnostics directory to save the diagnostics used on the test")
return
}
err = os.Rename(diagZip, filepath.Join(diagDir,
fmt.Sprintf("TestComponentBuildHashInDiagnostics-used-diag-%d.zip",
time.Now().Unix())))
if err != nil {
t.Logf("could not move diagnostics used in the test to %s: %v",
diagDir, err)
return
}
}()
stateFilePath := filepath.Join(diag, "state.yaml")
stateYAML, err := os.Open(stateFilePath)
require.NoError(t, err, "could not open diagnostics state.yaml")
defer func(stateYAML *os.File) {
err := stateYAML.Close()
assert.NoErrorf(t, err, "error closing %q", stateFilePath)
}(stateYAML)
state := struct {
Components []struct {
ID string `yaml:"id"`
State struct {
VersionInfo struct {
BuildHash string `yaml:"build_hash"`
Meta struct {
BuildTime string `yaml:"build_time"`
Commit string `yaml:"commit"`
} `yaml:"meta"`
Name string `yaml:"name"`
} `yaml:"version_info"`
} `yaml:"state"`
} `yaml:"components"`
}{}
err = yaml.NewDecoder(stateYAML).Decode(&state)
require.NoError(t, err, "could not parse state.yaml (%s)", stateYAML.Name())
for _, c := range state.Components {
assert.Equalf(t, wantBuildHash, c.State.VersionInfo.BuildHash,
"component %s: VersionInfo.BuildHash mismatch", c.ID)
assert.Equalf(t, wantBuildHash, c.State.VersionInfo.Meta.Commit,
"component %s: VersionInfo.Meta.Commit mismatch", c.ID)
}
if t.Failed() {
_, seek := stateYAML.Seek(0, 0)
if seek != nil {
t.Logf("could not reset state.yaml offset to print it")
return
}
data, err := io.ReadAll(stateYAML)
if err != nil {
t.Logf("could not read state.yaml: %v", err)
}
t.Logf("test failed: state.yaml contents: %q", string(data))
}
}
func testVersionWithRunningAgent(runCtx context.Context, f *atesting.Fixture) func(*testing.T) {
return func(t *testing.T) {
testf := func(ctx context.Context) error {
testAgentPackageVersion(ctx, f, false)
return nil
}
runAgentWithAfterTest(runCtx, f, t, testf)
}
}
func testVersionAfterUpdatingFile(runCtx context.Context, f *atesting.Fixture) func(*testing.T) {
return func(t *testing.T) {
pkgVersionFiles := findPkgVersionFiles(t, f.WorkDir())
testVersion := "1.2.3-test-abcdef"
for _, pkgVerFile := range pkgVersionFiles {
err := os.WriteFile(pkgVerFile, []byte(testVersion), 0o644)
require.NoError(t, err)
}
testf := func(ctx context.Context) error {
testAgentPackageVersion(ctx, f, false)
return nil
}
runAgentWithAfterTest(runCtx, f, t, testf)
}
}
func testAfterRemovingPkgVersionFiles(runCtx context.Context, f *atesting.Fixture) func(*testing.T) {
return func(t *testing.T) {
matches := findPkgVersionFiles(t, f.WorkDir())
for _, m := range matches {
t.Logf("removing package version file %q", m)
err := os.Remove(m)
require.NoErrorf(t, err, "error removing package version file %q", m)
}
testf := func(ctx context.Context) error {
// check the version returned by the running agent
stdout, stderr, processState := getAgentVersionOutput(t, f, ctx, false)
binaryActualVersion := unmarshalVersionOutput(t, stdout, "binary")
assert.Equal(t, version.GetDefaultVersion(), binaryActualVersion, "binary version does not return default beat version when the package version file is missing")
daemonActualVersion := unmarshalVersionOutput(t, stdout, "daemon")
assert.Equal(t, version.GetDefaultVersion(), daemonActualVersion, "daemon version does not return default beat version when the package version file is missing")
assert.True(t, processState.Success(), "elastic agent version command should be successful even if the pkg version is not found")
assert.Contains(t, string(stderr), "Error initializing version information")
return nil
}
runAgentWithAfterTest(runCtx, f, t, testf)
}
}
func runAgentWithAfterTest(runCtx context.Context, f *atesting.Fixture, t *testing.T, testf func(ctx context.Context) error) {
err := f.Run(runCtx, atesting.State{
AgentState: atesting.NewClientState(client.Healthy),
// we don't really need a config and a state but the testing fwk wants it anyway
Configure: simpleConfig2,
Components: map[string]atesting.ComponentState{
"fake-default": {
State: atesting.NewClientState(client.Healthy),
Units: map[atesting.ComponentUnitKey]atesting.ComponentUnitState{
{UnitType: client.UnitTypeOutput, UnitID: "fake-default"}: {
State: atesting.NewClientState(client.Healthy),
},
{UnitType: client.UnitTypeInput, UnitID: "fake-default-fake"}: {
State: atesting.NewClientState(client.Healthy),
},
},
},
},
After: testf,
})
require.NoError(t, err)
}
type StateComponentVersion struct {
Components []struct {
ID string `yaml:"id"`
State struct {
VersionInfo struct {
Meta struct {
BuildTime string `yaml:"build_time"`
Commit string `yaml:"commit"`
} `yaml:"meta"`
Name string `yaml:"name"`
} `yaml:"version_info"`
} `yaml:"state"`
} `yaml:"components"`
}