Skip to content

Commit c74420b

Browse files
authored
[System tests] Extract function to create all kibana policies required (#2881)
1 parent d26542a commit c74420b

File tree

1 file changed

+110
-95
lines changed

1 file changed

+110
-95
lines changed

internal/testrunner/runners/system/tester.go

Lines changed: 110 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -883,7 +883,7 @@ func (r *tester) getDeprecationWarnings(ctx context.Context, dataStream string)
883883
return result, nil
884884
}
885885

886-
func (r *tester) checkDeprecationWarnings(stackVersion *semver.Version, dataStream string, warnings []deprecationWarning, configName string) []testrunner.TestResult {
886+
func (r *tester) checkDeprecationWarnings(stackVersion *semver.Version, warnings []deprecationWarning, configName string) []testrunner.TestResult {
887887
var results []testrunner.TestResult
888888
for _, warning := range warnings {
889889
if ignoredDeprecationWarning(stackVersion, warning) {
@@ -1007,97 +1007,12 @@ func (r *tester) prepareScenario(ctx context.Context, config *testConfig, stackC
10071007
return nil, fmt.Errorf("failed to find the selected policy_template: %w", err)
10081008
}
10091009

1010-
// Configure package (single data stream) via Fleet APIs.
1011-
testTime := time.Now().Format("20060102T15:04:05Z")
1012-
var policyToTest, policyCurrent, policyToEnroll *kibana.Policy
1013-
if r.runTearDown || r.runTestsOnly {
1014-
policyCurrent = &serviceStateData.CurrentPolicy
1015-
policyToEnroll = &serviceStateData.EnrollPolicy
1016-
logger.Debugf("Got current policy from file: %q - %q", policyCurrent.Name, policyCurrent.ID)
1017-
} else {
1018-
// Created a specific Agent Policy to enrolling purposes
1019-
// There are some issues when the stack is running for some time,
1020-
// agents cannot enroll with the default policy
1021-
// This enroll policy must be created even if independent Elastic Agents are not used. Agents created
1022-
// in Kubernetes or Custom Agents require this enroll policy too (service deployer).
1023-
logger.Debug("creating enroll policy...")
1024-
policyEnroll := kibana.Policy{
1025-
Name: fmt.Sprintf("ep-test-system-enroll-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
1026-
Description: fmt.Sprintf("test policy created by elastic-package to enroll agent for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
1027-
Namespace: common.CreateTestRunID(),
1028-
}
1029-
1030-
policyToEnroll, err = r.kibanaClient.CreatePolicy(ctx, policyEnroll)
1031-
if err != nil {
1032-
return nil, fmt.Errorf("could not create test policy: %w", err)
1033-
}
1034-
}
1035-
1036-
r.deleteTestPolicyHandler = func(ctx context.Context) error {
1037-
// ensure that policyToEnroll policy gets deleted if the execution receives a signal
1038-
// before creating the test policy
1039-
// This handler is going to be redefined after creating the test policy
1040-
if r.runTestsOnly {
1041-
return nil
1042-
}
1043-
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
1044-
return fmt.Errorf("error cleaning up test policy: %w", err)
1045-
}
1046-
return nil
1047-
}
1048-
1049-
if r.runTearDown {
1050-
// required to assign the policy stored in the service state file
1051-
// so data stream related to this Agent Policy can be obtained (and deleted)
1052-
// in the cleanTestScenarioHandler handler
1053-
policyToTest = policyCurrent
1054-
} else {
1055-
// Create a specific Agent Policy just for testing this test.
1056-
// This allows us to ensure that the Agent Policy used for testing is
1057-
// assigned to the agent with all the required changes (e.g. Package DataStream)
1058-
logger.Debug("creating test policy...")
1059-
policy := kibana.Policy{
1060-
Name: fmt.Sprintf("ep-test-system-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
1061-
Description: fmt.Sprintf("test policy created by elastic-package test system for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
1062-
Namespace: common.CreateTestRunID(),
1063-
}
1064-
// 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
1065-
// TODO: Migrate from stack.logstash_enabled to the stack config.
1066-
if r.profile.Config("stack.logstash_enabled", "false") == "true" {
1067-
policy.DataOutputID = "fleet-logstash-output"
1068-
}
1069-
if stackConfig.OutputID != "" {
1070-
policy.DataOutputID = stackConfig.OutputID
1071-
}
1072-
policyToTest, err = r.kibanaClient.CreatePolicy(ctx, policy)
1073-
if err != nil {
1074-
return nil, fmt.Errorf("could not create test policy: %w", err)
1075-
}
1076-
}
1077-
1078-
r.deleteTestPolicyHandler = func(ctx context.Context) error {
1079-
logger.Debug("deleting test policies...")
1080-
if err := r.kibanaClient.DeletePolicy(ctx, policyToTest.ID); err != nil {
1081-
return fmt.Errorf("error cleaning up test policy: %w", err)
1082-
}
1083-
if r.runTestsOnly {
1084-
return nil
1085-
}
1086-
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
1087-
return fmt.Errorf("error cleaning up test policy: %w", err)
1088-
}
1089-
return nil
1090-
}
1091-
1092-
// policyToEnroll is used in both independent agents and agents created by servicedeployer (custom or kubernetes agents)
1093-
policy := policyToEnroll
1094-
if r.runTearDown || r.runTestsOnly {
1095-
// required in order to be able select the right agent in `checkEnrolledAgents` when
1096-
// using independent agents or custom/kubernetes agents since policy data is set into `agentInfo` variable`
1097-
policy = policyCurrent
1010+
policyToEnrollOrCurrent, policyToTest, err := r.createOrGetKibanaPolicies(ctx, serviceStateData, stackConfig)
1011+
if err != nil {
1012+
return nil, fmt.Errorf("failed to create kibana policies: %w", err)
10981013
}
10991014

1100-
agentDeployed, agentInfo, err := r.setupAgent(ctx, config, serviceStateData, policy)
1015+
agentDeployed, agentInfo, err := r.setupAgent(ctx, config, serviceStateData, policyToEnrollOrCurrent)
11011016
if err != nil {
11021017
return nil, err
11031018
}
@@ -1116,7 +1031,7 @@ func (r *tester) prepareScenario(ctx context.Context, config *testConfig, stackC
11161031
}
11171032
}
11181033

1119-
service, svcInfo, err := r.setupService(ctx, config, serviceOptions, svcInfo, agentInfo, agentDeployed, policy, serviceStateData)
1034+
service, svcInfo, err := r.setupService(ctx, config, serviceOptions, svcInfo, agentInfo, agentDeployed, policyToEnrollOrCurrent, serviceStateData)
11201035
if err != nil && !errors.Is(err, os.ErrNotExist) {
11211036
return nil, err
11221037
}
@@ -1318,7 +1233,7 @@ func (r *tester) prepareScenario(ctx context.Context, config *testConfig, stackC
13181233
if r.runSetup {
13191234
opts := scenarioStateOpts{
13201235
origPolicy: &origPolicy,
1321-
enrollPolicy: policyToEnroll,
1236+
enrollPolicy: policyToEnrollOrCurrent,
13221237
currentPolicy: policyToTest,
13231238
config: config,
13241239
agent: *origAgent,
@@ -1334,6 +1249,106 @@ func (r *tester) prepareScenario(ctx context.Context, config *testConfig, stackC
13341249
return &scenario, nil
13351250
}
13361251

1252+
// createOrGetKibanaPolicies creates the Kibana policies required for testing.
1253+
// It creates two policies, one for enrolling the agent (policyToEnroll) and another one
1254+
// for testing purposes (policyToTest) where the package data stream is added.
1255+
// In case the tester is running with --teardown or --no-provision flags, then the policies
1256+
// are read from the service state file created in the setup stage.
1257+
func (r *tester) createOrGetKibanaPolicies(ctx context.Context, serviceStateData ServiceState, stackConfig stack.Config) (*kibana.Policy, *kibana.Policy, error) {
1258+
// Configure package (single data stream) via Fleet APIs.
1259+
testTime := time.Now().Format("20060102T15:04:05Z")
1260+
var policyToTest, policyCurrent, policyToEnroll *kibana.Policy
1261+
var err error
1262+
1263+
if r.runTearDown || r.runTestsOnly {
1264+
policyCurrent = &serviceStateData.CurrentPolicy
1265+
policyToEnroll = &serviceStateData.EnrollPolicy
1266+
logger.Debugf("Got current policy from file: %q - %q", policyCurrent.Name, policyCurrent.ID)
1267+
} else {
1268+
// Created a specific Agent Policy to enrolling purposes
1269+
// There are some issues when the stack is running for some time,
1270+
// agents cannot enroll with the default policy
1271+
// This enroll policy must be created even if independent Elastic Agents are not used. Agents created
1272+
// in Kubernetes or Custom Agents require this enroll policy too (service deployer).
1273+
logger.Debug("creating enroll policy...")
1274+
policyEnroll := kibana.Policy{
1275+
Name: fmt.Sprintf("ep-test-system-enroll-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
1276+
Description: fmt.Sprintf("test policy created by elastic-package to enroll agent for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
1277+
Namespace: common.CreateTestRunID(),
1278+
}
1279+
1280+
policyToEnroll, err = r.kibanaClient.CreatePolicy(ctx, policyEnroll)
1281+
if err != nil {
1282+
return nil, nil, fmt.Errorf("could not create test policy: %w", err)
1283+
}
1284+
}
1285+
1286+
r.deleteTestPolicyHandler = func(ctx context.Context) error {
1287+
// ensure that policyToEnroll policy gets deleted if the execution receives a signal
1288+
// before creating the test policy
1289+
// This handler is going to be redefined after creating the test policy
1290+
if r.runTestsOnly {
1291+
return nil
1292+
}
1293+
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
1294+
return fmt.Errorf("error cleaning up test policy: %w", err)
1295+
}
1296+
return nil
1297+
}
1298+
1299+
if r.runTearDown {
1300+
// required to assign the policy stored in the service state file
1301+
// so data stream related to this Agent Policy can be obtained (and deleted)
1302+
// in the cleanTestScenarioHandler handler
1303+
policyToTest = policyCurrent
1304+
} else {
1305+
// Create a specific Agent Policy just for testing this test.
1306+
// This allows us to ensure that the Agent Policy used for testing is
1307+
// assigned to the agent with all the required changes (e.g. Package DataStream)
1308+
logger.Debug("creating test policy...")
1309+
policy := kibana.Policy{
1310+
Name: fmt.Sprintf("ep-test-system-%s-%s-%s-%s-%s", r.testFolder.Package, r.testFolder.DataStream, r.serviceVariant, r.configFileName, testTime),
1311+
Description: fmt.Sprintf("test policy created by elastic-package test system for data stream %s/%s", r.testFolder.Package, r.testFolder.DataStream),
1312+
Namespace: common.CreateTestRunID(),
1313+
}
1314+
// 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
1315+
// TODO: Migrate from stack.logstash_enabled to the stack config.
1316+
if r.profile.Config("stack.logstash_enabled", "false") == "true" {
1317+
policy.DataOutputID = "fleet-logstash-output"
1318+
}
1319+
if stackConfig.OutputID != "" {
1320+
policy.DataOutputID = stackConfig.OutputID
1321+
}
1322+
policyToTest, err = r.kibanaClient.CreatePolicy(ctx, policy)
1323+
if err != nil {
1324+
return nil, nil, fmt.Errorf("could not create test policy: %w", err)
1325+
}
1326+
}
1327+
1328+
r.deleteTestPolicyHandler = func(ctx context.Context) error {
1329+
logger.Debug("deleting test policies...")
1330+
if err := r.kibanaClient.DeletePolicy(ctx, policyToTest.ID); err != nil {
1331+
return fmt.Errorf("error cleaning up test policy: %w", err)
1332+
}
1333+
if r.runTestsOnly {
1334+
return nil
1335+
}
1336+
if err := r.kibanaClient.DeletePolicy(ctx, policyToEnroll.ID); err != nil {
1337+
return fmt.Errorf("error cleaning up test policy: %w", err)
1338+
}
1339+
return nil
1340+
}
1341+
1342+
if r.runTearDown || r.runTestsOnly {
1343+
// required to return "policyCurrent" policy in order to be able select the right agent in `checkEnrolledAgents` when
1344+
// using independent agents or custom/kubernetes agents since policy data is set into `agentInfo` variable`
1345+
return policyCurrent, policyToTest, nil
1346+
}
1347+
1348+
// policyToEnroll is used in both independent agents and agents created by servicedeployer (custom or kubernetes agents)
1349+
return policyToEnroll, policyToTest, nil
1350+
}
1351+
13371352
func (r *tester) setupService(ctx context.Context, config *testConfig, serviceOptions servicedeployer.FactoryOptions, svcInfo servicedeployer.ServiceInfo, agentInfo agentdeployer.AgentInfo, agentDeployed agentdeployer.DeployedAgent, policy *kibana.Policy, state ServiceState) (servicedeployer.DeployedService, servicedeployer.ServiceInfo, error) {
13381353
logger.Info("Setting up service...")
13391354
if r.runTearDown || r.runTestsOnly {
@@ -1668,7 +1683,7 @@ func (r *tester) validateTestScenario(ctx context.Context, result *testrunner.Re
16681683
}
16691684

16701685
// Check transforms if present
1671-
if err := r.checkTransforms(ctx, config, r.pkgManifest, scenario.kibanaDataStream, scenario.dataStream, scenario.syntheticEnabled); err != nil {
1686+
if err := r.checkTransforms(ctx, config, r.pkgManifest, scenario.dataStream, scenario.syntheticEnabled); err != nil {
16721687
results, _ := result.WithError(err)
16731688
return results, nil
16741689
}
@@ -1683,7 +1698,7 @@ func (r *tester) validateTestScenario(ctx context.Context, result *testrunner.Re
16831698
}
16841699
}
16851700

1686-
if results := r.checkDeprecationWarnings(stackVersion, scenario.dataStream, scenario.deprecationWarnings, config.Name()); len(results) > 0 {
1701+
if results := r.checkDeprecationWarnings(stackVersion, scenario.deprecationWarnings, config.Name()); len(results) > 0 {
16871702
return results, nil
16881703
}
16891704

@@ -2062,7 +2077,7 @@ func selectPolicyTemplateByName(policies []packages.PolicyTemplate, name string)
20622077
return packages.PolicyTemplate{}, fmt.Errorf("policy template %q not found", name)
20632078
}
20642079

2065-
func (r *tester) checkTransforms(ctx context.Context, config *testConfig, pkgManifest *packages.PackageManifest, ds kibana.PackageDataStream, dataStream string, syntheticEnabled bool) error {
2080+
func (r *tester) checkTransforms(ctx context.Context, config *testConfig, pkgManifest *packages.PackageManifest, dataStream string, syntheticEnabled bool) error {
20662081
if config.SkipTransformValidation {
20672082
return nil
20682083
}

0 commit comments

Comments
 (0)