-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathtester.go
2237 lines (1946 loc) · 70.5 KB
/
tester.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 system
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"gopkg.in/yaml.v3"
"github.com/elastic/elastic-package/internal/agentdeployer"
"github.com/elastic/elastic-package/internal/common"
"github.com/elastic/elastic-package/internal/configuration/locations"
"github.com/elastic/elastic-package/internal/elasticsearch"
"github.com/elastic/elastic-package/internal/elasticsearch/ingest"
"github.com/elastic/elastic-package/internal/environment"
"github.com/elastic/elastic-package/internal/fields"
"github.com/elastic/elastic-package/internal/formatter"
"github.com/elastic/elastic-package/internal/kibana"
"github.com/elastic/elastic-package/internal/logger"
"github.com/elastic/elastic-package/internal/multierror"
"github.com/elastic/elastic-package/internal/packages"
"github.com/elastic/elastic-package/internal/profile"
"github.com/elastic/elastic-package/internal/resources"
"github.com/elastic/elastic-package/internal/servicedeployer"
"github.com/elastic/elastic-package/internal/stack"
"github.com/elastic/elastic-package/internal/testrunner"
"github.com/elastic/elastic-package/internal/wait"
)
const (
checkFieldsBody = `{
"fields": ["*"],
"runtime_mappings": {
"my_ignored": {
"type": "keyword",
"script": {
"source": "for (def v : params['_fields']._ignored.values) { emit(v); }"
}
}
},
"aggs": {
"all_ignored": {
"filter": {
"exists": {
"field": "_ignored"
}
},
"aggs": {
"ignored_fields": {
"terms": {
"size": 100,
"field": "my_ignored"
}
},
"ignored_docs": {
"top_hits": {
"size": 5
}
}
}
}
}
}`
DevDeployDir = "_dev/deploy"
// TestType defining system tests
TestType testrunner.TestType = "system"
// Maximum number of events to query.
elasticsearchQuerySize = 500
// ServiceLogsAgentDir is folder path where log files produced by the service
// are stored on the Agent container's filesystem.
ServiceLogsAgentDir = "/tmp/service_logs"
waitForDataDefaultTimeout = 10 * time.Minute
)
type logsRegexp struct {
includes *regexp.Regexp
excludes []*regexp.Regexp
}
type logsByContainer struct {
containerName string
patterns []logsRegexp
}
var (
errorPatterns = []logsByContainer{
{
containerName: "elastic-agent",
patterns: []logsRegexp{
{
includes: regexp.MustCompile("^Cannot index event publisher.Event"),
excludes: []*regexp.Regexp{
// this regex is excluded to ensure that logs coming from the `system` package installed by default are not taken into account
regexp.MustCompile(`action \[indices:data\/write\/bulk\[s\]\] is unauthorized for API key id \[.*\] of user \[.*\] on indices \[.*\], this action is granted by the index privileges \[.*\]`),
},
},
{
includes: regexp.MustCompile("->(FAILED|DEGRADED)"),
// this regex is excluded to avoid a regresion in 8.11 that can make a component to pass to a degraded state during some seconds after reassigning or removing a policy
excludes: []*regexp.Regexp{
regexp.MustCompile(`Component state changed .* \(HEALTHY->DEGRADED\): Degraded: pid .* missed .* check-in`),
},
},
},
},
}
enableIndependentAgents = environment.WithElasticPackagePrefix("TEST_ENABLE_INDEPENDENT_AGENT")
)
type tester struct {
profile *profile.Profile
testFolder testrunner.TestFolder
packageRootPath string
generateTestResult bool
esAPI *elasticsearch.API
esClient *elasticsearch.Client
kibanaClient *kibana.Client
runIndependentElasticAgent bool
deferCleanup time.Duration
serviceVariant string
configFileName string
runSetup bool
runTearDown bool
runTestsOnly bool
pipelines []ingest.Pipeline
dataStreamPath string
stackVersion kibana.VersionInfo
locationManager *locations.LocationManager
resourcesManager *resources.Manager
pkgManifest *packages.PackageManifest
dataStreamManifest *packages.DataStreamManifest
withCoverage bool
coverageType string
checkFailureStore bool
serviceStateFilePath string
globalTestConfig testrunner.GlobalRunnerTestConfig
// Execution order of following handlers is defined in runner.TearDown() method.
removeAgentHandler func(context.Context) error
deleteTestPolicyHandler func(context.Context) error
cleanTestScenarioHandler func(context.Context) error
resetAgentPolicyHandler func(context.Context) error
resetAgentLogLevelHandler func(context.Context) error
shutdownServiceHandler func(context.Context) error
shutdownAgentHandler func(context.Context) error
}
type SystemTesterOptions struct {
Profile *profile.Profile
TestFolder testrunner.TestFolder
PackageRootPath string
GenerateTestResult bool
API *elasticsearch.API
KibanaClient *kibana.Client
// FIXME: Keeping Elasticsearch client to be able to do low-level requests for parameters not supported yet by the API.
ESClient *elasticsearch.Client
DeferCleanup time.Duration
ServiceVariant string
ConfigFileName string
GlobalTestConfig testrunner.GlobalRunnerTestConfig
WithCoverage bool
CoverageType string
CheckFailureStore bool
RunSetup bool
RunTearDown bool
RunTestsOnly bool
}
func NewSystemTester(options SystemTesterOptions) (*tester, error) {
r := tester{
profile: options.Profile,
testFolder: options.TestFolder,
packageRootPath: options.PackageRootPath,
generateTestResult: options.GenerateTestResult,
esAPI: options.API,
esClient: options.ESClient,
kibanaClient: options.KibanaClient,
deferCleanup: options.DeferCleanup,
serviceVariant: options.ServiceVariant,
configFileName: options.ConfigFileName,
runSetup: options.RunSetup,
runTestsOnly: options.RunTestsOnly,
runTearDown: options.RunTearDown,
globalTestConfig: options.GlobalTestConfig,
withCoverage: options.WithCoverage,
coverageType: options.CoverageType,
checkFailureStore: options.CheckFailureStore,
runIndependentElasticAgent: true,
}
r.resourcesManager = resources.NewManager()
r.resourcesManager.RegisterProvider(resources.DefaultKibanaProviderName, &resources.KibanaProvider{Client: r.kibanaClient})
r.serviceStateFilePath = filepath.Join(stateFolderPath(r.profile.ProfilePath), serviceStateFileName)
var err error
r.locationManager, err = locations.NewLocationManager()
if err != nil {
return nil, fmt.Errorf("reading service logs directory failed: %w", err)
}
r.dataStreamPath, _, err = packages.FindDataStreamRootForPath(r.testFolder.Path)
if err != nil {
return nil, fmt.Errorf("locating data stream root failed: %w", err)
}
if r.esAPI == nil {
return nil, errors.New("missing Elasticsearch client")
}
if r.kibanaClient == nil {
return nil, errors.New("missing Kibana client")
}
r.stackVersion, err = r.kibanaClient.Version()
if err != nil {
return nil, fmt.Errorf("cannot request Kibana version: %w", err)
}
r.pkgManifest, err = packages.ReadPackageManifestFromPackageRoot(r.packageRootPath)
if err != nil {
return nil, fmt.Errorf("reading package manifest failed: %w", err)
}
r.dataStreamManifest, err = packages.ReadDataStreamManifest(filepath.Join(r.dataStreamPath, packages.DataStreamManifestFile))
if err != nil {
return nil, fmt.Errorf("reading data stream manifest failed: %w", err)
}
// If the environment variable is present, it always has preference over the root
// privileges value (if any) defined in the manifest file
v, ok := os.LookupEnv(enableIndependentAgents)
if ok {
r.runIndependentElasticAgent = strings.ToLower(v) == "true"
}
return &r, nil
}
// Ensures that runner implements testrunner.Tester interface
var _ testrunner.Tester = new(tester)
// Type returns the type of test that can be run by this test runner.
func (r *tester) Type() testrunner.TestType {
return TestType
}
// String returns the human-friendly name of the test runner.
func (r *tester) String() string {
return "system"
}
// Parallel indicates if this tester can run in parallel or not.
func (r tester) Parallel() bool {
// it is required independent Elastic Agents to run in parallel system tests
return r.runIndependentElasticAgent && r.globalTestConfig.Parallel
}
// Run runs the system tests defined under the given folder
func (r *tester) Run(ctx context.Context) ([]testrunner.TestResult, error) {
if !r.runSetup && !r.runTearDown && !r.runTestsOnly {
return r.run(ctx)
}
result := r.newResult("(init)")
svcInfo, err := r.createServiceInfo()
if err != nil {
return result.WithError(err)
}
configFile := filepath.Join(r.testFolder.Path, r.configFileName)
testConfig, err := newConfig(configFile, svcInfo, r.serviceVariant)
if err != nil {
return nil, fmt.Errorf("unable to load system test case file '%s': %w", configFile, err)
}
logger.Debugf("Using config: %q", testConfig.Name())
resultName := ""
switch {
case r.runSetup:
resultName = "setup"
case r.runTearDown:
resultName = "teardown"
case r.runTestsOnly:
resultName = "tests"
}
result = r.newResult(fmt.Sprintf("%s - %s", resultName, testConfig.Name()))
scenario, err := r.prepareScenario(ctx, testConfig, svcInfo)
if r.runSetup && err != nil {
tdErr := r.tearDownTest(ctx)
if tdErr != nil {
logger.Errorf("failed to tear down runner: %s", tdErr.Error())
}
setupDirErr := r.removeServiceStateFile()
if setupDirErr != nil {
logger.Error(err.Error())
}
return result.WithError(err)
}
if r.runTestsOnly {
if err != nil {
return result.WithError(fmt.Errorf("failed to prepare scenario: %w", err))
}
results, err := r.validateTestScenario(ctx, result, scenario, testConfig)
tdErr := r.tearDownTest(ctx)
if tdErr != nil {
logger.Errorf("failed to tear down runner: %s", tdErr.Error())
}
return results, err
}
if r.runTearDown {
if err != nil {
logger.Errorf("failed to prepare scenario: %s", err.Error())
logger.Errorf("continue with the tear down process")
}
if err := r.tearDownTest(ctx); err != nil {
return result.WithError(err)
}
err := r.removeServiceStateFile()
if err != nil {
return result.WithError(err)
}
}
return result.WithSuccess()
}
type resourcesOptions struct {
installedPackage bool
}
func (r *tester) createAgentOptions(policyName string) agentdeployer.FactoryOptions {
return agentdeployer.FactoryOptions{
Profile: r.profile,
PackageRootPath: r.packageRootPath,
DataStreamRootPath: r.dataStreamPath,
DevDeployDir: DevDeployDir,
Type: agentdeployer.TypeTest,
StackVersion: r.stackVersion.Version(),
PackageName: r.testFolder.Package,
DataStream: r.testFolder.DataStream,
PolicyName: policyName,
RunTearDown: r.runTearDown,
RunTestsOnly: r.runTestsOnly,
RunSetup: r.runSetup,
}
}
func (r *tester) createServiceOptions(variantName string) servicedeployer.FactoryOptions {
return servicedeployer.FactoryOptions{
Profile: r.profile,
PackageRootPath: r.packageRootPath,
DataStreamRootPath: r.dataStreamPath,
DevDeployDir: DevDeployDir,
Variant: variantName,
Type: servicedeployer.TypeTest,
StackVersion: r.stackVersion.Version(),
RunTearDown: r.runTearDown,
RunTestsOnly: r.runTestsOnly,
RunSetup: r.runSetup,
DeployIndependentAgent: r.runIndependentElasticAgent,
}
}
func (r *tester) createAgentInfo(policy *kibana.Policy, config *testConfig, runID string, agentManifest packages.Agent) (agentdeployer.AgentInfo, error) {
var info agentdeployer.AgentInfo
info.Name = r.testFolder.Package
info.Logs.Folder.Agent = ServiceLogsAgentDir
info.Test.RunID = runID
folderName := fmt.Sprintf("agent-%s", r.testFolder.Package)
if r.testFolder.DataStream != "" {
folderName = fmt.Sprintf("%s-%s", folderName, r.testFolder.DataStream)
}
folderName = fmt.Sprintf("%s-%s", folderName, runID)
dirPath, err := agentdeployer.CreateServiceLogsDir(r.profile, folderName)
if err != nil {
return agentdeployer.AgentInfo{}, fmt.Errorf("failed to create service logs dir: %w", err)
}
info.Logs.Folder.Local = dirPath
info.Policy.Name = policy.Name
info.Policy.ID = policy.ID
// Copy all agent settings from the test configuration file
info.Agent.AgentSettings = config.Agent.AgentSettings
// If user is defined in the configuration file, it has preference
// and it should not be overwritten by the value in the manifest
if info.Agent.User == "" && agentManifest.Privileges.Root {
info.Agent.User = "root"
}
return info, nil
}
func (r *tester) createServiceInfo() (servicedeployer.ServiceInfo, error) {
var svcInfo servicedeployer.ServiceInfo
svcInfo.Name = r.testFolder.Package
svcInfo.Logs.Folder.Local = r.locationManager.ServiceLogDir()
svcInfo.Logs.Folder.Agent = ServiceLogsAgentDir
svcInfo.Test.RunID = common.CreateTestRunID()
if r.runTearDown || r.runTestsOnly {
logger.Debug("Skip creating output directory")
} else {
outputDir, err := servicedeployer.CreateOutputDir(r.locationManager, svcInfo.Test.RunID)
if err != nil {
return servicedeployer.ServiceInfo{}, fmt.Errorf("could not create output dir for terraform deployer %w", err)
}
svcInfo.OutputDir = outputDir
}
svcInfo.Agent.Independent = false
return svcInfo, nil
}
// TearDown method doesn't perform any global action as the "tear down" is executed per test case.
func (r *tester) TearDown(ctx context.Context) error {
return nil
}
func (r *tester) tearDownTest(ctx context.Context) error {
if r.deferCleanup > 0 {
logger.Debugf("waiting for %s before tearing down...", r.deferCleanup)
select {
case <-time.After(r.deferCleanup):
case <-ctx.Done():
}
}
// Avoid cancellations during cleanup.
cleanupCtx := context.WithoutCancel(ctx)
// This handler should be run before shutting down Elastic Agents (agent deployer)
// or services that could run agents like Custom Agents (service deployer)
// or Kind deployer.
if r.resetAgentPolicyHandler != nil {
if err := r.resetAgentPolicyHandler(cleanupCtx); err != nil {
return err
}
r.resetAgentPolicyHandler = nil
}
// Shutting down the service should be run one of the first actions
// to ensure that resources created by terraform are deleted even if other
// errors fail.
if r.shutdownServiceHandler != nil {
if err := r.shutdownServiceHandler(cleanupCtx); err != nil {
return err
}
r.shutdownServiceHandler = nil
}
if r.cleanTestScenarioHandler != nil {
if err := r.cleanTestScenarioHandler(cleanupCtx); err != nil {
return err
}
r.cleanTestScenarioHandler = nil
}
if r.resetAgentLogLevelHandler != nil {
if err := r.resetAgentLogLevelHandler(cleanupCtx); err != nil {
return err
}
r.resetAgentLogLevelHandler = nil
}
if r.removeAgentHandler != nil {
if err := r.removeAgentHandler(cleanupCtx); err != nil {
return err
}
r.removeAgentHandler = nil
}
if r.deleteTestPolicyHandler != nil {
if err := r.deleteTestPolicyHandler(cleanupCtx); err != nil {
return err
}
r.deleteTestPolicyHandler = nil
}
if r.shutdownAgentHandler != nil {
if err := r.shutdownAgentHandler(cleanupCtx); err != nil {
return err
}
r.shutdownAgentHandler = nil
}
return nil
}
func (r *tester) newResult(name string) *testrunner.ResultComposer {
return testrunner.NewResultComposer(testrunner.TestResult{
TestType: TestType,
Name: name,
Package: r.testFolder.Package,
DataStream: r.testFolder.DataStream,
})
}
func (r *tester) run(ctx context.Context) (results []testrunner.TestResult, err error) {
result := r.newResult("(init)")
startTesting := time.Now()
results, err = r.runTestPerVariant(ctx, result, r.configFileName, r.serviceVariant)
if err != nil {
return results, err
}
// Every tester is in charge of just one test, so if there is no error,
// then there should be just one result for tests. As an exception, there could
// be two results if there is any issue checking Elastic Agent logs.
if len(results) > 0 && results[0].Skipped != nil {
logger.Debugf("Test skipped, avoid checking agent logs")
return results, nil
}
tempDir, err := os.MkdirTemp("", "test-system-")
if err != nil {
return nil, fmt.Errorf("can't create temporal directory: %w", err)
}
defer os.RemoveAll(tempDir)
stackConfig, err := stack.LoadConfig(r.profile)
if err != nil {
return nil, err
}
provider, err := stack.BuildProvider(stackConfig.Provider, r.profile)
if err != nil {
return nil, fmt.Errorf("failed to build stack provider: %w", err)
}
dumpOptions := stack.DumpOptions{
Output: tempDir,
Profile: r.profile,
}
dump, err := provider.Dump(context.WithoutCancel(ctx), dumpOptions)
if err != nil {
return nil, fmt.Errorf("dump failed: %w", err)
}
logResults, err := r.checkAgentLogs(dump, startTesting, errorPatterns)
if err != nil {
return result.WithError(err)
}
results = append(results, logResults...)
return results, nil
}
func (r *tester) runTestPerVariant(ctx context.Context, result *testrunner.ResultComposer, cfgFile, variantName string) ([]testrunner.TestResult, error) {
svcInfo, err := r.createServiceInfo()
if err != nil {
return result.WithError(err)
}
configFile := filepath.Join(r.testFolder.Path, cfgFile)
testConfig, err := newConfig(configFile, svcInfo, variantName)
if err != nil {
return nil, fmt.Errorf("unable to load system test case file '%s': %w", configFile, err)
}
logger.Debugf("Using config: %q", testConfig.Name())
partial, err := r.runTest(ctx, testConfig, svcInfo)
tdErr := r.tearDownTest(ctx)
if err != nil {
return partial, err
}
if tdErr != nil {
return partial, fmt.Errorf("failed to tear down runner: %w", tdErr)
}
return partial, nil
}
func isSyntheticSourceModeEnabled(ctx context.Context, api *elasticsearch.API, dataStreamName string) (bool, error) {
// We append a suffix so we don't use an existing resource, what may cause conflicts in old versions of
// Elasticsearch, such as https://github.com/elastic/elasticsearch/issues/84256.
resp, err := api.Indices.SimulateIndexTemplate(dataStreamName+"simulated",
api.Indices.SimulateIndexTemplate.WithContext(ctx),
)
if err != nil {
return false, fmt.Errorf("could not simulate index template for %s: %w", dataStreamName, err)
}
defer resp.Body.Close()
if resp.IsError() {
return false, fmt.Errorf("could not simulate index template for %s: %s", dataStreamName, resp.String())
}
var results struct {
Template struct {
Mappings struct {
Source struct {
Mode string `json:"mode"`
} `json:"_source"`
} `json:"mappings"`
Settings struct {
Index struct {
Mode string `json:"mode"`
} `json:"index"`
} `json:"settings"`
} `json:"template"`
}
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return false, fmt.Errorf("could not decode index template simulation response: %w", err)
}
if results.Template.Mappings.Source.Mode == "synthetic" {
return true, nil
}
// It seems that some index modes enable synthetic source mode even when it is not explicitly mentioned
// in the mappings. So assume that when these index modes are used, the synthetic mode is also used.
var syntheticsIndexModes = []string{
"logs", // Replaced in 8.15.0 with "logsdb", see https://github.com/elastic/elasticsearch/pull/111054
"logsdb",
"time_series",
}
if slices.Contains(syntheticsIndexModes, results.Template.Settings.Index.Mode) {
return true, nil
}
return false, nil
}
type hits struct {
Source []common.MapStr `json:"_source"`
Fields []common.MapStr `json:"fields"`
IgnoredFields []string
DegradedDocs []common.MapStr
}
func (h hits) getDocs(syntheticsEnabled bool) []common.MapStr {
if syntheticsEnabled {
return h.Fields
}
return h.Source
}
func (h hits) size() int {
return len(h.Source)
}
func (r *tester) getDocs(ctx context.Context, dataStream string) (*hits, error) {
resp, err := r.esAPI.Search(
r.esAPI.Search.WithContext(ctx),
r.esAPI.Search.WithIndex(dataStream),
r.esAPI.Search.WithSort("@timestamp:asc"),
r.esAPI.Search.WithSize(elasticsearchQuerySize),
r.esAPI.Search.WithSource("true"),
r.esAPI.Search.WithBody(strings.NewReader(checkFieldsBody)),
r.esAPI.Search.WithIgnoreUnavailable(true),
)
if err != nil {
return nil, fmt.Errorf("could not search data stream: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusServiceUnavailable && strings.Contains(resp.String(), "no_shard_available_action_exception") {
// Index is being created, but no shards are available yet.
// See https://github.com/elastic/elasticsearch/issues/65846
return &hits{}, nil
}
if resp.IsError() {
return nil, fmt.Errorf("failed to search docs for data stream %s: %s", dataStream, resp.String())
}
var results struct {
Hits struct {
Total struct {
Value int
}
Hits []struct {
Source common.MapStr `json:"_source"`
Fields common.MapStr `json:"fields"`
}
}
Aggregations struct {
AllIgnored struct {
DocCount int `json:"doc_count"`
IgnoredFields struct {
Buckets []struct {
Key string `json:"key"`
} `json:"buckets"`
} `json:"ignored_fields"`
IgnoredDocs struct {
Hits struct {
Hits []common.MapStr `json:"hits"`
} `json:"hits"`
} `json:"ignored_docs"`
} `json:"all_ignored"`
} `json:"aggregations"`
Error *struct {
Type string
Reason string
}
Status int
}
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return nil, fmt.Errorf("could not decode search results response: %w", err)
}
numHits := results.Hits.Total.Value
if results.Error != nil {
logger.Debugf("found %d hits in %s data stream: %s: %s Status=%d",
numHits, dataStream, results.Error.Type, results.Error.Reason, results.Status)
} else {
logger.Debugf("found %d hits in %s data stream", numHits, dataStream)
}
var hits hits
for _, hit := range results.Hits.Hits {
hits.Source = append(hits.Source, hit.Source)
hits.Fields = append(hits.Fields, hit.Fields)
}
for _, bucket := range results.Aggregations.AllIgnored.IgnoredFields.Buckets {
hits.IgnoredFields = append(hits.IgnoredFields, bucket.Key)
}
hits.DegradedDocs = results.Aggregations.AllIgnored.IgnoredDocs.Hits.Hits
return &hits, nil
}
func (r *tester) getFailureStoreDocs(ctx context.Context, dataStream string) ([]failureStoreDocument, error) {
query := map[string]any{
"query": map[string]any{
"bool": map[string]any{
// Ignoring failures with error.type version_conflict_engine_exception because there are packages which
// explicitly set the _id with the fingerprint processor to avoid duplicates.
"must_not": map[string]any{
"term": map[string]any{
"error.type": "version_conflict_engine_exception",
},
},
},
},
}
body, err := json.Marshal(query)
if err != nil {
return nil, fmt.Errorf("failed to encode search query: %w", err)
}
// FIXME: Using the low-level transport till the API SDK supports the failure store.
request, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/%s/_search?failure_store=only", dataStream), bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create search request: %w", err)
}
request.Header.Set("Content-Type", "application/json")
resp, err := r.esClient.Transport.Perform(request)
if err != nil {
return nil, fmt.Errorf("failed to perform search request: %w", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusNotFound:
// Can happen if the data stream hasn't been created yet.
return nil, nil
case resp.StatusCode == http.StatusServiceUnavailable:
// Index is being created, but no shards are available yet.
// See https://github.com/elastic/elasticsearch/issues/65846
return nil, nil
case resp.StatusCode >= 400:
return nil, fmt.Errorf("search request returned status code %d", resp.StatusCode)
}
var results struct {
Hits struct {
Hits []struct {
Source failureStoreDocument `json:"_source"`
Fields common.MapStr `json:"fields"`
} `json:"hits"`
} `json:"hits"`
}
err = json.NewDecoder(resp.Body).Decode(&results)
if err != nil {
return nil, fmt.Errorf("failed to decode search response: %w", err)
}
var docs []failureStoreDocument
for _, hit := range results.Hits.Hits {
docs = append(docs, hit.Source)
}
return docs, nil
}
type scenarioTest struct {
dataStream string
policyTemplateName string
kibanaDataStream kibana.PackageDataStream
syntheticEnabled bool
docs []common.MapStr
failureStore []failureStoreDocument
ignoredFields []string
degradedDocs []common.MapStr
agent agentdeployer.DeployedAgent
startTestTime time.Time
}
type failureStoreDocument struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
StackTrace string `json:"stack_trace"`
PipelineTrace []string `json:"pipeline_trace"`
Pipeline string `json:"pipeline"`
ProcessorType string `json:"processor_type"`
} `json:"error"`
}
func (r *tester) deleteDataStream(ctx context.Context, dataStream string) error {
resp, err := r.esAPI.Indices.DeleteDataStream([]string{dataStream},
r.esAPI.Indices.DeleteDataStream.WithContext(ctx),
)
if err != nil {
return fmt.Errorf("delete request failed for data stream %s: %w", dataStream, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
// Data stream doesn't exist, there was nothing to do.
return nil
}
if resp.IsError() {
return fmt.Errorf("delete request failed for data stream %s: %s", dataStream, resp.String())
}
return nil
}
func (r *tester) prepareScenario(ctx context.Context, config *testConfig, svcInfo servicedeployer.ServiceInfo) (*scenarioTest, error) {
serviceOptions := r.createServiceOptions(config.ServiceVariantName)
var err error
var serviceStateData ServiceState
if r.runSetup {
err = r.createServiceStateDir()
if err != nil {
return nil, fmt.Errorf("failed to create setup services dir: %w", err)
}
}
scenario := scenarioTest{}
if r.runTearDown || r.runTestsOnly {
serviceStateData, err = readServiceStateData(r.serviceStateFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read service setup data: %w", err)
}
}
serviceOptions.DeployIndependentAgent = r.runIndependentElasticAgent
policyTemplateName := config.PolicyTemplate
if policyTemplateName == "" {
policyTemplateName, err = findPolicyTemplateForInput(*r.pkgManifest, *r.dataStreamManifest, config.Input)
if err != nil {
return nil, fmt.Errorf("failed to determine the associated policy_template: %w", err)
}
}
scenario.policyTemplateName = policyTemplateName
policyTemplate, err := selectPolicyTemplateByName(r.pkgManifest.PolicyTemplates, scenario.policyTemplateName)
if err != nil {
return nil, fmt.Errorf("failed to find the selected policy_template: %w", err)
}
// Configure package (single data stream) via Fleet APIs.
testTime := time.Now().Format("20060102T15:04:05Z")
var policyToTest, policyCurrent, policyToEnroll *kibana.Policy
if r.runTearDown || r.runTestsOnly {
policyCurrent = &serviceStateData.CurrentPolicy
policyToEnroll = &serviceStateData.EnrollPolicy
logger.Debugf("Got current policy from file: %q - %q", policyCurrent.Name, policyCurrent.ID)
} else {
// Created a specific Agent Policy to enrolling purposes
// There are some issues when the stack is running for some time,
// agents cannot enroll with the default policy
// This enroll policy must be created even if independent Elastic Agents are not used. Agents created
// in Kubernetes or Custom Agents require this enroll policy too (service deployer).
logger.Debug("creating enroll policy...")
policyEnroll := kibana.Policy{
Name: fmt.Sprintf("ep-test-system-enroll-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
Description: fmt.Sprintf("test policy created by elastic-package to enroll agent for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
Namespace: common.CreateTestRunID(),
}
policyToEnroll, err = r.kibanaClient.CreatePolicy(ctx, policyEnroll)
if err != nil {
return nil, fmt.Errorf("could not create test policy: %w", err)
}
}
r.deleteTestPolicyHandler = func(ctx context.Context) error {
// ensure that policyToEnroll policy gets deleted if the execution receives a signal
// before creating the test policy
// This handler is going to be redefined after creating the test policy
if r.runTestsOnly {
return nil
}
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
return fmt.Errorf("error cleaning up test policy: %w", err)
}
return nil
}
if r.runTearDown {
// required to assign the policy stored in the service state file
// so data stream related to this Agent Policy can be obtained (and deleted)
// in the cleanTestScenarioHandler handler
policyToTest = policyCurrent
} else {
// Create a specific Agent Policy just for testing this test.
// This allows us to ensure that the Agent Policy used for testing is
// assigned to the agent with all the required changes (e.g. Package DataStream)
logger.Debug("creating test policy...")
policy := kibana.Policy{
Name: fmt.Sprintf("ep-test-system-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
Description: fmt.Sprintf("test policy created by elastic-package test system for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
Namespace: common.CreateTestRunID(),
}
// Assign the data_output_id to the agent policy to configure the output to logstash. The value is inferred from stack/_static/kibana.yml.tmpl
if r.profile.Config("stack.logstash_enabled", "false") == "true" {
policy.DataOutputID = "fleet-logstash-output"
}
policyToTest, err = r.kibanaClient.CreatePolicy(ctx, policy)
if err != nil {
return nil, fmt.Errorf("could not create test policy: %w", err)
}
}
r.deleteTestPolicyHandler = func(ctx context.Context) error {
logger.Debug("deleting test policies...")
if err := r.kibanaClient.DeletePolicy(ctx, policyToTest.ID); err != nil {
return fmt.Errorf("error cleaning up test policy: %w", err)
}
if r.runTestsOnly {
return nil
}
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
return fmt.Errorf("error cleaning up test policy: %w", err)
}
return nil
}
// policyToEnroll is used in both independent agents and agents created by servicedeployer (custom or kubernetes agents)
policy := policyToEnroll
if r.runTearDown || r.runTestsOnly {
// required in order to be able select the right agent in `checkEnrolledAgents` when
// using independent agents or custom/kubernetes agents since policy data is set into `agentInfo` variable`
policy = policyCurrent
}
agentDeployed, agentInfo, err := r.setupAgent(ctx, config, serviceStateData, policy, r.pkgManifest.Agent)
if err != nil {
return nil, err
}