This repository has been archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
fleet.go
1740 lines (1447 loc) · 51.7 KB
/
fleet.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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/google/uuid"
"go.elastic.co/apm"
"github.com/cenkalti/backoff/v4"
"github.com/cucumber/godog"
"github.com/elastic/e2e-testing/internal/common"
"github.com/elastic/e2e-testing/internal/deploy"
"github.com/elastic/e2e-testing/internal/elasticsearch"
"github.com/elastic/e2e-testing/internal/installer"
"github.com/elastic/e2e-testing/internal/kibana"
"github.com/elastic/e2e-testing/internal/shell"
"github.com/elastic/e2e-testing/internal/utils"
"github.com/elastic/e2e-testing/pkg/downloads"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const actionADDED = "added"
const actionREMOVED = "removed"
const testResourcesDir = "./testresources"
var deployedAgentsCount = 0
// FleetTestSuite represents the scenarios for Fleet-mode
type FleetTestSuite struct {
// integrations
KibanaProfile string
StandAlone bool
CurrentToken string // current enrollment token
CurrentTokenID string // current enrollment tokenID
ElasticAgentStopped bool // will be used to signal when the agent process can be called again in the tear-down stage
Image string // base image used to install the agent
InstallerType string
Integration kibana.IntegrationPackage // the installed integration
Policy kibana.Policy
PolicyUpdatedAt string // the moment the policy was updated
Version string // current elastic-agent version
kibanaClient *kibana.Client
deployer deploy.Deployment
BeatsProcess string // (optional) name of the Beats that must be present before installing the elastic-agent
// date controls for queries
AgentStoppedDate time.Time
RuntimeDependenciesStartDate time.Time
// instrumentation
currentContext context.Context
DefaultAPIKey string
}
// afterScenario destroys the state created by a scenario
func (fts *FleetTestSuite) afterScenario() {
defer func() {
fts.DefaultAPIKey = ""
// Reset Kibana Profile to default
fts.KibanaProfile = ""
deployedAgentsCount = 0
}()
span := tx.StartSpan("Clean up", "test.scenario.clean", nil)
fts.currentContext = apm.ContextWithSpan(context.Background(), span)
defer span.End()
serviceName := common.ElasticAgentServiceName
if fts.InstallerType != "" {
agentService := deploy.NewServiceRequest(serviceName)
if !fts.StandAlone {
// for the centos/debian flavour we need to retrieve the internal log files for the elastic-agent, as they are not
// exposed as container logs. For that reason we need to go through the installer abstraction
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, fts.InstallerType)
if log.IsLevelEnabled(log.DebugLevel) {
err := agentInstaller.Logs(fts.currentContext)
if err != nil {
log.WithField("error", err).Warn("Could not get agent logs in the container")
}
}
// only call it when the elastic-agent is present
if !fts.ElasticAgentStopped {
err := agentInstaller.Uninstall(fts.currentContext)
if err != nil {
log.Warnf("Could not uninstall the agent after the scenario: %v", err)
}
}
} else if log.IsLevelEnabled(log.DebugLevel) {
// for the Docker image, we simply retrieve container logs
_ = fts.deployer.Logs(fts.currentContext, agentService)
}
err := fts.unenrollHostname()
if err != nil {
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
log.WithFields(log.Fields{
"err": err,
"hostname": manifest.Hostname,
}).Warn("The agentIDs for the hostname could not be unenrolled")
}
}
env := fts.getProfileEnv()
_ = fts.deployer.Remove(fts.currentContext, deploy.NewServiceRequest(common.FleetProfileName), []deploy.ServiceRequest{deploy.NewServiceRequest(serviceName)}, env)
// TODO: Determine why this may be empty here before being cleared out
if fts.CurrentTokenID != "" {
err := fts.kibanaClient.DeleteEnrollmentAPIKey(fts.currentContext, fts.CurrentTokenID)
if err != nil {
log.WithFields(log.Fields{
"err": err,
"tokenID": fts.CurrentTokenID,
}).Warn("The enrollment token could not be deleted")
}
}
// TODO: Dont think this is needed if we are making all policies unique
// fts.kibanaClient.DeleteAllPolicies(fts.currentContext)
// clean up fields
fts.CurrentTokenID = ""
fts.CurrentToken = ""
fts.InstallerType = ""
fts.Image = ""
fts.StandAlone = false
fts.BeatsProcess = ""
}
// beforeScenario creates the state needed by a scenario
func (fts *FleetTestSuite) beforeScenario() {
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute
exp := utils.GetExponentialBackOff(maxTimeout)
fts.StandAlone = false
fts.ElasticAgentStopped = false
fts.Version = common.BeatVersion
waitForPolicy := func() error {
policy, err := fts.kibanaClient.CreatePolicy(fts.currentContext)
if err != nil {
return errors.Wrap(err, "A new policy could not be obtained, retrying.")
}
log.WithFields(log.Fields{
"id": policy.ID,
"name": policy.Name,
"description": policy.Description,
}).Info("Policy created")
fts.Policy = policy
// Grab the system integration as we'll need to assign it a new name so it wont collide during
// multiple policy creations at once
integration, err := fts.kibanaClient.GetIntegrationByPackageName(context.Background(), "system")
if err != nil {
return err
}
packageDataStream := kibana.PackageDataStream{
Name: fmt.Sprintf("%s-%s", integration.Name, uuid.New().String()),
Description: integration.Title,
Namespace: "default",
PolicyID: fts.Policy.ID,
Enabled: true,
Package: integration,
Inputs: []kibana.Input{},
}
systemMetricsFile := filepath.Join(testResourcesDir, "/default_system_metrics.json")
jsonData, err := readJSONFile(systemMetricsFile)
if err != nil {
return err
}
for _, item := range jsonData.Children() {
var streams []kibana.Stream
if err := json.Unmarshal(item.Path("streams").Bytes(), &streams); err != nil {
return err
}
if item.Path("type").Data().(string) == "system/metrics" {
packageDataStream.Inputs = append(packageDataStream.Inputs, kibana.Input{
Type: item.Path("type").Data().(string),
Enabled: item.Path("enabled").Data().(bool),
Streams: streams,
Vars: map[string]kibana.Var{
"system.hostfs": {
Value: "",
Type: "text",
},
},
})
} else {
packageDataStream.Inputs = append(packageDataStream.Inputs, kibana.Input{
Type: item.Path("type").Data().(string),
Enabled: item.Path("enabled").Data().(bool),
Streams: streams,
})
}
}
err = fts.kibanaClient.AddIntegrationToPolicy(context.Background(), packageDataStream)
if err != nil {
return err
}
return nil
}
err := backoff.Retry(waitForPolicy, exp)
if err != nil {
log.Fatal(err)
}
// Grab a new enrollment key for new agent
enrollmentKey, err := fts.kibanaClient.CreateEnrollmentAPIKey(fts.currentContext, fts.Policy)
if err != nil {
log.Fatal("Unable to create enrollment token for agent")
}
fts.CurrentToken = enrollmentKey.APIKey
fts.CurrentTokenID = enrollmentKey.ID
}
func (fts *FleetTestSuite) contributeSteps(s *godog.ScenarioContext) {
s.Step(`^kibana uses "([^"]*)" profile$`, fts.kibanaUsesProfile)
s.Step(`^agent uses enrollment token from "([^"]*)" policy$`, fts.agentUsesPolicy)
s.Step(`^a "([^"]*)" agent is deployed to Fleet$`, fts.anAgentIsDeployedToFleet)
s.Step(`^an agent is deployed to Fleet on top of "([^"]*)"$`, fts.anAgentIsDeployedToFleetOnTopOfBeat)
s.Step(`^an agent is deployed to Fleet with "([^"]*)" installer$`, fts.anAgentIsDeployedToFleetWithInstaller)
s.Step(`^an agent "([^"]*)" is deployed to Fleet with "([^"]*)" installer$`, fts.anStaleAgentIsDeployedToFleetWithInstaller)
s.Step(`^agent is in version "([^"]*)"$`, fts.agentInVersion)
s.Step(`^agent is upgraded to version "([^"]*)"$`, fts.anAgentIsUpgraded)
s.Step(`^the agent is listed in Fleet as "([^"]*)"$`, fts.theAgentIsListedInFleetWithStatus)
s.Step(`^the default API key has "([^"]*)"$`, fts.verifyDefaultAPIKey)
s.Step(`^the host is restarted$`, fts.theHostIsRestarted)
s.Step(`^system package dashboards are listed in Fleet$`, fts.systemPackageDashboardsAreListedInFleet)
s.Step(`^the agent is un-enrolled$`, fts.theAgentIsUnenrolled)
s.Step(`^the agent is re-enrolled on the host$`, fts.theAgentIsReenrolledOnTheHost)
s.Step(`^the enrollment token is revoked$`, fts.theEnrollmentTokenIsRevoked)
s.Step(`^an attempt to enroll a new agent fails$`, fts.anAttemptToEnrollANewAgentFails)
s.Step(`^the "([^"]*)" process is "([^"]*)" on the host$`, fts.processStateChangedOnTheHost)
s.Step(`^the file system Agent folder is empty$`, fts.theFileSystemAgentFolderIsEmpty)
s.Step(`^certs are installed$`, fts.installCerts)
s.Step(`^a Linux data stream exists with some data$`, fts.checkDataStream)
s.Step(`^the agent is enrolled into "([^"]*)" policy$`, fts.agentRunPolicy)
// endpoint steps
s.Step(`^the "([^"]*)" integration is "([^"]*)" in the policy$`, fts.theIntegrationIsOperatedInThePolicy)
s.Step(`^the "([^"]*)" datasource is shown in the policy as added$`, fts.thePolicyShowsTheDatasourceAdded)
s.Step(`^the host name is shown in the Administration view in the Security App as "([^"]*)"$`, fts.theHostNameIsShownInTheAdminViewInTheSecurityApp)
s.Step(`^the host name is not shown in the Administration view in the Security App$`, fts.theHostNameIsNotShownInTheAdminViewInTheSecurityApp)
s.Step(`^an "([^"]*)" is successfully deployed with an Agent using "([^"]*)" installer$`, fts.anIntegrationIsSuccessfullyDeployedWithAgentAndInstaller)
s.Step(`^the policy response will be shown in the Security App$`, fts.thePolicyResponseWillBeShownInTheSecurityApp)
s.Step(`^the policy is updated to have "([^"]*)" in "([^"]*)" mode$`, fts.thePolicyIsUpdatedToHaveMode)
s.Step(`^the policy will reflect the change in the Security App$`, fts.thePolicyWillReflectTheChangeInTheSecurityApp)
// System Integration steps
s.Step(`^the policy is updated to have "([^"]*)" set to "([^"]*)"$`, fts.thePolicyIsUpdatedToHaveSystemSet)
s.Step(`^"([^"]*)" with "([^"]*)" metrics are present in the datastreams$`, fts.theMetricsInTheDataStream)
// stand-alone only steps
s.Step(`^a "([^"]*)" stand-alone agent is deployed$`, fts.aStandaloneAgentIsDeployed)
s.Step(`^a "([^"]*)" stand-alone agent is deployed with fleet server mode$`, fts.bootstrapFleetServerFromAStandaloneAgent)
s.Step(`^there is new data in the index from agent$`, fts.thereIsNewDataInTheIndexFromAgent)
s.Step(`^the "([^"]*)" docker container is stopped$`, fts.theDockerContainerIsStopped)
s.Step(`^there is no new data in the index after agent shuts down$`, fts.thereIsNoNewDataInTheIndexAfterAgentShutsDown)
s.Step(`^the stand-alone agent is listed in Fleet as "([^"]*)"$`, fts.theStandaloneAgentIsListedInFleetWithStatus)
}
func (fts *FleetTestSuite) theStandaloneAgentIsListedInFleetWithStatus(desiredStatus string) error {
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute
exp := utils.GetExponentialBackOff(maxTimeout)
retryCount := 0
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
waitForAgents := func() error {
retryCount++
agents, err := fts.kibanaClient.ListAgents(fts.currentContext)
if err != nil {
return err
}
if len(agents) == 0 {
return errors.New("No agents found")
}
for _, agent := range agents {
hostname := agent.LocalMetadata.Host.HostName
if hostname == manifest.Hostname {
return theAgentIsListedInFleetWithStatus(fts.currentContext, desiredStatus, hostname)
}
}
err = errors.New("Agent not found in Fleet")
log.WithFields(log.Fields{
"elapsedTime": exp.GetElapsedTime(),
"hostname": manifest.Hostname,
"retries": retryCount,
}).Warn(err)
return err
}
err := backoff.Retry(waitForAgents, exp)
if err != nil {
return err
}
return nil
}
func (fts *FleetTestSuite) anStaleAgentIsDeployedToFleetWithInstaller(version, installerType string) error {
agentVersionBackup := fts.Version
defer func() { fts.Version = agentVersionBackup }()
common.AgentStaleVersion = shell.GetEnv("ELASTIC_AGENT_STALE_VERSION", common.AgentStaleVersion)
// check if stale version is an alias
v, err := downloads.GetElasticArtifactVersion(common.AgentStaleVersion)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"version": common.AgentStaleVersion,
}).Error("Failed to get stale version")
return err
}
common.AgentStaleVersion = v
useCISnapshots := downloads.GithubCommitSha1 != ""
if useCISnapshots && !strings.HasSuffix(common.AgentStaleVersion, "-SNAPSHOT") {
common.AgentStaleVersion += "-SNAPSHOT"
}
switch version {
case "stale":
version = common.AgentStaleVersion
case "latest":
version = common.BeatVersion
default:
version = common.AgentStaleVersion
}
fts.Version = version
return fts.anAgentIsDeployedToFleetWithInstaller(installerType)
}
func (fts *FleetTestSuite) installCerts() error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, fts.InstallerType)
err := agentInstaller.InstallCerts(fts.currentContext)
if err != nil {
log.WithFields(log.Fields{
"agentVersion": common.BeatVersion,
"agentStaleVersion": common.AgentStaleVersion,
"error": err,
"installer": agentInstaller,
"version": fts.Version,
}).Error("Could not install the certificates")
return err
}
return nil
}
func (fts *FleetTestSuite) anAgentIsUpgraded(desiredVersion string) error {
switch desiredVersion {
case "stale":
desiredVersion = common.AgentStaleVersion
case "latest":
desiredVersion = common.BeatVersion
default:
desiredVersion = common.BeatVersion
}
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
return fts.kibanaClient.UpgradeAgent(fts.currentContext, manifest.Hostname, desiredVersion)
}
func (fts *FleetTestSuite) agentInVersion(version string) error {
switch version {
case "stale":
version = common.AgentStaleVersion
case "latest":
version = downloads.GetSnapshotVersion(common.BeatVersion)
}
agentInVersionFn := func() error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
agent, err := fts.kibanaClient.GetAgentByHostname(fts.currentContext, manifest.Hostname)
if err != nil {
return err
}
retrievedVersion := agent.LocalMetadata.Elastic.Agent.Version
if isSnapshot := agent.LocalMetadata.Elastic.Agent.Snapshot; isSnapshot {
retrievedVersion += "-SNAPSHOT"
}
if retrievedVersion != version {
return fmt.Errorf("version mismatch required '%s' retrieved '%s'", version, retrievedVersion)
}
return nil
}
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute * 2
exp := utils.GetExponentialBackOff(maxTimeout)
return backoff.Retry(agentInVersionFn, exp)
}
func (fts *FleetTestSuite) agentRunPolicy(policyName string) error {
agentRunPolicyFn := func() error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
policies, err := fts.kibanaClient.ListPolicies(fts.currentContext)
if err != nil {
return err
}
var policy *kibana.Policy
for _, p := range policies {
if policyName == p.Name {
policy = &p
break
}
}
if policy == nil {
return fmt.Errorf("Policy not found '%s'", policyName)
}
agent, err := fts.kibanaClient.GetAgentByHostname(fts.currentContext, manifest.Hostname)
if err != nil {
return err
}
if agent.PolicyID != policy.ID {
log.Errorf("FOUND %s %s", agent.PolicyID, policy.ID)
return fmt.Errorf("Agent not running the correct policy (running '%s' instead of '%s')", agent.PolicyID, policy.ID)
}
return nil
}
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute * 2
exp := utils.GetExponentialBackOff(maxTimeout)
return backoff.Retry(agentRunPolicyFn, exp)
}
// this step infers the installer type from the underlying OS image
// supported images: centos and debian
func (fts *FleetTestSuite) anAgentIsDeployedToFleet(image string) error {
installerType := "rpm"
if image == "debian" {
installerType = "deb"
}
fts.BeatsProcess = ""
// FIXME: We need to cleanup the steps to support different operating systems
// for now we will force the zip installer type when the agent is running on windows
if runtime.GOOS == "windows" && common.Provider == "remote" {
installerType = "zip"
}
return fts.anAgentIsDeployedToFleetWithInstallerAndFleetServer(installerType)
}
func (fts *FleetTestSuite) anAgentIsDeployedToFleetOnTopOfBeat(beatsProcess string) error {
installerType := "tar"
// FIXME: We need to cleanup the steps to support different operating systems
// for now we will force the zip installer type when the agent is running on windows
if runtime.GOOS == "windows" && common.Provider == "remote" {
installerType = "zip"
}
fts.BeatsProcess = beatsProcess
return fts.anAgentIsDeployedToFleetWithInstallerAndFleetServer(installerType)
}
// supported installers: tar, rpm, deb
func (fts *FleetTestSuite) anAgentIsDeployedToFleetWithInstaller(installerType string) error {
fts.BeatsProcess = ""
// FIXME: We need to cleanup the steps to support different operating systems
// for now we will force the zip installer type when the agent is running on windows
if runtime.GOOS == "windows" && common.Provider == "remote" {
installerType = "zip"
}
return fts.anAgentIsDeployedToFleetWithInstallerAndFleetServer(installerType)
}
func (fts *FleetTestSuite) anAgentIsDeployedToFleetWithInstallerAndFleetServer(installerType string) error {
log.WithFields(log.Fields{
"installer": installerType,
}).Trace("Deploying an agent to Fleet with base image using an already bootstrapped Fleet Server")
deployedAgentsCount++
fts.InstallerType = installerType
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName).WithScale(deployedAgentsCount)
if fts.BeatsProcess != "" {
agentService = agentService.WithBackgroundProcess(fts.BeatsProcess)
}
services := []deploy.ServiceRequest{
agentService,
}
env := fts.getProfileEnv()
err := fts.deployer.Add(fts.currentContext, deploy.NewServiceRequest(common.FleetProfileName), services, env)
if err != nil {
return err
}
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, installerType)
err = deployAgentToFleet(fts.currentContext, agentInstaller, fts.CurrentToken)
if err != nil {
return err
}
return err
}
func (fts *FleetTestSuite) processStateChangedOnTheHost(process string, state string) error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, fts.InstallerType)
if state == "started" {
err := agentInstaller.Start(fts.currentContext)
return err
} else if state == "restarted" {
err := agentInstaller.Stop(fts.currentContext)
if err != nil {
return err
}
err = agentInstaller.Start(fts.currentContext)
if err != nil {
return err
}
return nil
} else if state == "uninstalled" {
err := agentInstaller.Uninstall(fts.currentContext)
if err != nil {
return err
}
// signal that the elastic-agent was uninstalled
if process == common.ElasticAgentProcessName {
fts.ElasticAgentStopped = true
}
return nil
} else if state != "stopped" {
return godog.ErrPending
}
log.WithFields(log.Fields{
"service": agentService.Name,
"process": process,
}).Trace("Stopping process on the service")
err := agentInstaller.Stop(fts.currentContext)
if err != nil {
log.WithFields(log.Fields{
"action": state,
"error": err,
"service": agentService.Name,
"process": process,
}).Error("Could not stop process on the host")
return err
}
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
var srv deploy.ServiceRequest
if fts.StandAlone {
srv = deploy.NewServiceContainerRequest(manifest.Name)
} else {
srv = deploy.NewServiceRequest(manifest.Name)
}
return CheckProcessState(fts.currentContext, fts.deployer, srv, process, "stopped", 0)
}
// bootstrapFleet this method creates the runtime dependencies for the Fleet test suite, being of special
// interest kibana profile passed as part of the environment variables to bootstrap the dependencies.
func bootstrapFleet(ctx context.Context, env map[string]string) error {
deployer := deploy.New(common.Provider)
if profile, ok := env["kibanaProfile"]; ok {
log.Infof("Running kibana with %s profile", profile)
}
// the runtime dependencies must be started only in non-remote executions
return deployer.Bootstrap(ctx, deploy.NewServiceRequest(common.FleetProfileName), env, func() error {
kibanaClient, err := kibana.NewClient()
if err != nil {
log.WithFields(log.Fields{
"error": err,
"env": env,
}).Fatal("Unable to create kibana client")
}
err = elasticsearch.WaitForClusterHealth(ctx)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Elasticsearch Cluster is not healthy")
}
err = kibanaClient.RecreateFleet(ctx)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"env": env,
}).Fatal("Fleet could not be recreated")
}
serviceToken, err := elasticsearch.GetAPIToken(ctx)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Could not get API Token from Elasticsearch")
}
fleetServerEnv := make(map[string]string)
for k, v := range env {
fleetServerEnv[k] = v
}
fleetServerEnv["fleetServerMode"] = "1"
fleetServerEnv["fleetServerPort"] = "8220"
fleetServerEnv["fleetInsecure"] = "1"
fleetServerEnv["fleetServerServiceToken"] = serviceToken.AccessToken
fleetServerSrv := deploy.ServiceRequest{
Name: common.ElasticAgentServiceName,
Flavour: "fleet-server",
}
err = deployer.Add(ctx, deploy.NewServiceRequest(common.FleetProfileName), []deploy.ServiceRequest{fleetServerSrv}, fleetServerEnv)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"env": fleetServerEnv,
}).Fatal("Fleet Server could not be started")
}
err = kibanaClient.WaitForFleet(ctx)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"env": env,
}).Fatal("Fleet could not be initialized")
}
return nil
})
}
// kibanaUsesProfile this step should be ideally called as a Background or a Given clause, so that it
// is executed before any other in the test scenario. It will configure the Kibana profile to be used
// in the scenario, changing the configuration file to be used.
func (fts *FleetTestSuite) kibanaUsesProfile(profile string) error {
fts.KibanaProfile = profile
env := fts.getProfileEnv()
return bootstrapFleet(context.Background(), env)
}
func (fts *FleetTestSuite) getProfileEnv() map[string]string {
env := map[string]string{}
for k, v := range common.ProfileEnv {
env[k] = v
}
if fts.KibanaProfile != "" {
env["kibanaProfile"] = fts.KibanaProfile
}
return env
}
func (fts *FleetTestSuite) agentUsesPolicy(policyName string) error {
agentUsesPolicyFn := func() error {
policies, err := fts.kibanaClient.ListPolicies(fts.currentContext)
if err != nil {
return err
}
for _, p := range policies {
if policyName == p.Name {
fts.Policy = p
break
}
}
if fts.Policy.Name != policyName {
return fmt.Errorf("Policy not found '%s'", policyName)
}
return nil
}
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute * 2
exp := utils.GetExponentialBackOff(maxTimeout)
return backoff.Retry(agentUsesPolicyFn, exp)
}
func (fts *FleetTestSuite) setup() error {
log.Trace("Creating Fleet setup")
err := fts.kibanaClient.RecreateFleet(fts.currentContext)
if err != nil {
return err
}
return nil
}
func (fts *FleetTestSuite) theAgentIsListedInFleetWithStatus(desiredStatus string) error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
manifest, _ := fts.deployer.Inspect(fts.currentContext, agentService)
err := theAgentIsListedInFleetWithStatus(fts.currentContext, desiredStatus, manifest.Hostname)
if err != nil {
return err
}
if desiredStatus == "online" {
//get Agent Default Key
err := fts.theAgentGetDefaultAPIKey()
if err != nil {
return err
}
}
return err
}
func (fts *FleetTestSuite) theAgentGetDefaultAPIKey() error {
defaultAPIKey, _ := fts.getAgentDefaultAPIKey()
log.WithFields(log.Fields{
"default_api_key": defaultAPIKey,
}).Info("The Agent is installed with Default Api Key")
fts.DefaultAPIKey = defaultAPIKey
return nil
}
func (fts *FleetTestSuite) verifyDefaultAPIKey(status string) error {
newDefaultAPIKey, _ := fts.getAgentDefaultAPIKey()
logFields := log.Fields{
"new_default_api_key": newDefaultAPIKey,
"old_default_api_key": fts.DefaultAPIKey,
}
defaultAPIKeyHasChanged := (newDefaultAPIKey != fts.DefaultAPIKey)
if status == "changed" {
if !defaultAPIKeyHasChanged {
log.WithFields(logFields).Error("Integration added and Default API Key do not change")
return errors.New("Integration added and Default API Key do not change")
}
log.WithFields(logFields).Infof("Default API Key has %s when the Integration has been added", status)
return nil
}
if status == "not changed" {
if defaultAPIKeyHasChanged {
log.WithFields(logFields).Error("Integration updated and Default API Key is changed")
return errors.New("Integration updated and Default API Key is changed")
}
log.WithFields(logFields).Infof("Default API Key has %s when the Integration has been updated", status)
return nil
}
log.Warnf("Status %s is not supported yet", status)
return godog.ErrPending
}
func theAgentIsListedInFleetWithStatus(ctx context.Context, desiredStatus string, hostname string) error {
log.Tracef("Checking if agent is listed in Fleet as %s", desiredStatus)
kibanaClient, err := kibana.NewClient()
if err != nil {
return err
}
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute * 2
retryCount := 1
exp := utils.GetExponentialBackOff(maxTimeout)
agentOnlineFn := func() error {
agentID, err := kibanaClient.GetAgentIDByHostname(ctx, hostname)
if err != nil {
retryCount++
return err
}
if agentID == "" {
// the agent is not listed in Fleet
if desiredStatus == "offline" || desiredStatus == "inactive" {
log.WithFields(log.Fields{
"elapsedTime": exp.GetElapsedTime(),
"hostname": hostname,
"retries": retryCount,
"status": desiredStatus,
}).Info("The Agent is not present in Fleet, as expected")
return nil
}
retryCount++
return fmt.Errorf("the agent is not present in Fleet in the '%s' status, but it should", desiredStatus)
}
agentStatus, err := kibanaClient.GetAgentStatusByHostname(ctx, hostname)
isAgentInStatus := strings.EqualFold(agentStatus, desiredStatus)
if err != nil || !isAgentInStatus {
if err == nil {
err = fmt.Errorf("the Agent is not in the %s status yet", desiredStatus)
}
log.WithFields(log.Fields{
"agentID": agentID,
"isAgentInStatus": isAgentInStatus,
"elapsedTime": exp.GetElapsedTime(),
"hostname": hostname,
"retry": retryCount,
"status": desiredStatus,
}).Warn(err.Error())
retryCount++
return err
}
log.WithFields(log.Fields{
"isAgentInStatus": isAgentInStatus,
"elapsedTime": exp.GetElapsedTime(),
"hostname": hostname,
"retries": retryCount,
"status": desiredStatus,
}).Info("The Agent is in the desired status")
return nil
}
err = backoff.Retry(agentOnlineFn, exp)
if err != nil {
return err
}
return nil
}
func (fts *FleetTestSuite) theFileSystemAgentFolderIsEmpty() error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, fts.InstallerType)
pkgManifest, _ := agentInstaller.Inspect()
cmd := []string{
"ls", "-l", pkgManifest.WorkDir,
}
content, err := agentInstaller.Exec(fts.currentContext, cmd)
if err != nil {
if content == "" || strings.Contains(content, "No such file or directory") {
return nil
}
return err
}
log.WithFields(log.Fields{
"installer": agentInstaller,
"workingDir": pkgManifest.WorkDir,
"content": content,
}).Debug("Agent working dir content")
return fmt.Errorf("the file system directory is not empty")
}
func (fts *FleetTestSuite) theHostIsRestarted() error {
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
err := fts.deployer.Stop(fts.currentContext, agentService)
if err != nil {
log.WithField("err", err).Error("Could not stop the service")
}
utils.Sleep(time.Duration(utils.TimeoutFactor) * 10 * time.Second)
err = fts.deployer.Start(fts.currentContext, agentService)
if err != nil {
log.WithField("err", err).Error("Could not start the service")
}
log.Debug("The elastic-agent service has been restarted")
return nil
}
func (fts *FleetTestSuite) systemPackageDashboardsAreListedInFleet() error {
log.Trace("Checking system Package dashboards in Fleet")
dataStreamsCount := 0
maxTimeout := time.Duration(utils.TimeoutFactor) * time.Minute
retryCount := 1
exp := utils.GetExponentialBackOff(maxTimeout)
countDataStreamsFn := func() error {
dataStreams, err := fts.kibanaClient.GetDataStreams(fts.currentContext)
if err != nil {
log.WithFields(log.Fields{
"retry": retryCount,
"elapsedTime": exp.GetElapsedTime(),
}).Warn(err.Error())
retryCount++
return err
}
count := len(dataStreams.Children())
if count == 0 {
err = fmt.Errorf("there are no datastreams yet")
log.WithFields(log.Fields{
"retry": retryCount,
"dataStreams": count,
"elapsedTime": exp.GetElapsedTime(),
}).Warn(err.Error())
retryCount++
return err
}
log.WithFields(log.Fields{
"elapsedTime": exp.GetElapsedTime(),
"datastreams": count,
"retries": retryCount,
}).Info("Datastreams are present")
dataStreamsCount = count
return nil
}
err := backoff.Retry(countDataStreamsFn, exp)
if err != nil {
return err
}
if dataStreamsCount == 0 {
err = fmt.Errorf("there are no datastreams. We expected to have more than one")
log.Error(err.Error())
return err
}
return nil
}
func (fts *FleetTestSuite) theAgentIsUnenrolled() error {
return fts.unenrollHostname()
}
func (fts *FleetTestSuite) theAgentIsReenrolledOnTheHost() error {
log.Trace("Re-enrolling the agent on the host with same token")
agentService := deploy.NewServiceRequest(common.ElasticAgentServiceName)
agentInstaller, _ := installer.Attach(fts.currentContext, fts.deployer, agentService, fts.InstallerType)
err := agentInstaller.Enroll(fts.currentContext, fts.CurrentToken)