github.com/SAP/jenkins-library@v1.362.0/cmd/mavenExecuteIntegration_generated.go (about)

     1  // Code generated by piper's step-generator. DO NOT EDIT.
     2  
     3  package cmd
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"reflect"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/SAP/jenkins-library/pkg/config"
    13  	"github.com/SAP/jenkins-library/pkg/gcs"
    14  	"github.com/SAP/jenkins-library/pkg/log"
    15  	"github.com/SAP/jenkins-library/pkg/splunk"
    16  	"github.com/SAP/jenkins-library/pkg/telemetry"
    17  	"github.com/SAP/jenkins-library/pkg/validation"
    18  	"github.com/bmatcuk/doublestar"
    19  	"github.com/spf13/cobra"
    20  )
    21  
    22  type mavenExecuteIntegrationOptions struct {
    23  	Retry                       int    `json:"retry,omitempty"`
    24  	ForkCount                   string `json:"forkCount,omitempty"`
    25  	Goal                        string `json:"goal,omitempty"`
    26  	InstallArtifacts            bool   `json:"installArtifacts,omitempty"`
    27  	ProjectSettingsFile         string `json:"projectSettingsFile,omitempty"`
    28  	GlobalSettingsFile          string `json:"globalSettingsFile,omitempty"`
    29  	M2Path                      string `json:"m2Path,omitempty"`
    30  	LogSuccessfulMavenTransfers bool   `json:"logSuccessfulMavenTransfers,omitempty"`
    31  }
    32  
    33  type mavenExecuteIntegrationReports struct {
    34  }
    35  
    36  func (p *mavenExecuteIntegrationReports) persist(stepConfig mavenExecuteIntegrationOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    37  	if gcsBucketId == "" {
    38  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    39  		return
    40  	}
    41  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    42  	content := []gcs.ReportOutputParam{
    43  		{FilePattern: "**/requirement.mapping", ParamRef: "", StepResultType: "requirement-mapping"},
    44  		{FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "junit"},
    45  		{FilePattern: "**/integration-test/*.xml", ParamRef: "", StepResultType: "integration-test"},
    46  		{FilePattern: "**/jacoco.xml", ParamRef: "", StepResultType: "jacoco-coverage"},
    47  	}
    48  	envVars := []gcs.EnvVar{
    49  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    50  	}
    51  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    52  	if err != nil {
    53  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    54  		return
    55  	}
    56  	defer gcsClient.Close()
    57  	structVal := reflect.ValueOf(&stepConfig).Elem()
    58  	inputParameters := map[string]string{}
    59  	for i := 0; i < structVal.NumField(); i++ {
    60  		field := structVal.Type().Field(i)
    61  		if field.Type.String() == "string" {
    62  			paramName := strings.Split(field.Tag.Get("json"), ",")
    63  			paramValue, _ := structVal.Field(i).Interface().(string)
    64  			inputParameters[paramName[0]] = paramValue
    65  		}
    66  	}
    67  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    68  		log.Entry().Errorf("failed to persist reports: %v", err)
    69  	}
    70  }
    71  
    72  // MavenExecuteIntegrationCommand This step will execute backend integration tests via the Jacoco Maven-plugin.
    73  func MavenExecuteIntegrationCommand() *cobra.Command {
    74  	const STEP_NAME = "mavenExecuteIntegration"
    75  
    76  	metadata := mavenExecuteIntegrationMetadata()
    77  	var stepConfig mavenExecuteIntegrationOptions
    78  	var startTime time.Time
    79  	var reports mavenExecuteIntegrationReports
    80  	var logCollector *log.CollectorHook
    81  	var splunkClient *splunk.Splunk
    82  	telemetryClient := &telemetry.Telemetry{}
    83  
    84  	var createMavenExecuteIntegrationCmd = &cobra.Command{
    85  		Use:   STEP_NAME,
    86  		Short: "This step will execute backend integration tests via the Jacoco Maven-plugin.",
    87  		Long: `If the project contains a Maven module named "integration-tests", this step will execute
    88  the integration tests via the Jacoco Maven-plugin.`,
    89  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    90  			startTime = time.Now()
    91  			log.SetStepName(STEP_NAME)
    92  			log.SetVerbose(GeneralConfig.Verbose)
    93  
    94  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    95  
    96  			path, _ := os.Getwd()
    97  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    98  			log.RegisterHook(fatalHook)
    99  
   100  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
   101  			if err != nil {
   102  				log.SetErrorCategory(log.ErrorConfiguration)
   103  				return err
   104  			}
   105  
   106  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   107  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   108  				log.RegisterHook(&sentryHook)
   109  			}
   110  
   111  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   112  				splunkClient = &splunk.Splunk{}
   113  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   114  				log.RegisterHook(logCollector)
   115  			}
   116  
   117  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   118  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   119  			}
   120  
   121  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   122  			if err != nil {
   123  				return err
   124  			}
   125  			if err = validation.ValidateStruct(stepConfig); err != nil {
   126  				log.SetErrorCategory(log.ErrorConfiguration)
   127  				return err
   128  			}
   129  
   130  			return nil
   131  		},
   132  		Run: func(_ *cobra.Command, _ []string) {
   133  			stepTelemetryData := telemetry.CustomData{}
   134  			stepTelemetryData.ErrorCode = "1"
   135  			handler := func() {
   136  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   137  				config.RemoveVaultSecretFiles()
   138  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   139  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   140  				stepTelemetryData.PiperCommitHash = GitCommit
   141  				telemetryClient.SetData(&stepTelemetryData)
   142  				telemetryClient.Send()
   143  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   144  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   145  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   146  						GeneralConfig.HookConfig.SplunkConfig.Token,
   147  						GeneralConfig.HookConfig.SplunkConfig.Index,
   148  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   149  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   150  				}
   151  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   152  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   153  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   154  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   155  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   156  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   157  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   158  				}
   159  			}
   160  			log.DeferExitHandler(handler)
   161  			defer handler()
   162  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   163  			mavenExecuteIntegration(stepConfig, &stepTelemetryData)
   164  			stepTelemetryData.ErrorCode = "0"
   165  			log.Entry().Info("SUCCESS")
   166  		},
   167  	}
   168  
   169  	addMavenExecuteIntegrationFlags(createMavenExecuteIntegrationCmd, &stepConfig)
   170  	return createMavenExecuteIntegrationCmd
   171  }
   172  
   173  func addMavenExecuteIntegrationFlags(cmd *cobra.Command, stepConfig *mavenExecuteIntegrationOptions) {
   174  	cmd.Flags().IntVar(&stepConfig.Retry, "retry", 1, "The number of times that integration tests will be retried before failing the step. Note: This will consume more time for the step execution.")
   175  	cmd.Flags().StringVar(&stepConfig.ForkCount, "forkCount", `1C`, "The number of JVM processes that are spawned to run the tests in parallel in case of using a maven based project structure. For more details visit the Surefire documentation at https://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#forkCount.")
   176  	cmd.Flags().StringVar(&stepConfig.Goal, "goal", `test`, "The name of the Maven goal to execute.")
   177  	cmd.Flags().BoolVar(&stepConfig.InstallArtifacts, "installArtifacts", true, "If enabled, it will install all artifacts to the local maven repository to make them available before running the tests. This is required if the integration test module has dependencies to other modules in the repository and they were not installed before.")
   178  	cmd.Flags().StringVar(&stepConfig.ProjectSettingsFile, "projectSettingsFile", os.Getenv("PIPER_projectSettingsFile"), "Path to the mvn settings file that should be used as project settings file.")
   179  	cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
   180  	cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "Path to the location of the local repository that should be used.")
   181  	cmd.Flags().BoolVar(&stepConfig.LogSuccessfulMavenTransfers, "logSuccessfulMavenTransfers", false, "Configures maven to log successful downloads. This is set to `false` by default to reduce the noise in build logs.")
   182  
   183  }
   184  
   185  // retrieve step metadata
   186  func mavenExecuteIntegrationMetadata() config.StepData {
   187  	var theMetaData = config.StepData{
   188  		Metadata: config.StepMetadata{
   189  			Name:        "mavenExecuteIntegration",
   190  			Aliases:     []config.Alias{{Name: "mavenExecute", Deprecated: false}},
   191  			Description: "This step will execute backend integration tests via the Jacoco Maven-plugin.",
   192  		},
   193  		Spec: config.StepSpec{
   194  			Inputs: config.StepInputs{
   195  				Parameters: []config.StepParameters{
   196  					{
   197  						Name:        "retry",
   198  						ResourceRef: []config.ResourceReference{},
   199  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   200  						Type:        "int",
   201  						Mandatory:   false,
   202  						Aliases:     []config.Alias{},
   203  						Default:     1,
   204  					},
   205  					{
   206  						Name:        "forkCount",
   207  						ResourceRef: []config.ResourceReference{},
   208  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   209  						Type:        "string",
   210  						Mandatory:   false,
   211  						Aliases:     []config.Alias{},
   212  						Default:     `1C`,
   213  					},
   214  					{
   215  						Name:        "goal",
   216  						ResourceRef: []config.ResourceReference{},
   217  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   218  						Type:        "string",
   219  						Mandatory:   false,
   220  						Aliases:     []config.Alias{},
   221  						Default:     `test`,
   222  					},
   223  					{
   224  						Name:        "installArtifacts",
   225  						ResourceRef: []config.ResourceReference{},
   226  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   227  						Type:        "bool",
   228  						Mandatory:   false,
   229  						Aliases:     []config.Alias{},
   230  						Default:     true,
   231  					},
   232  					{
   233  						Name:        "projectSettingsFile",
   234  						ResourceRef: []config.ResourceReference{},
   235  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   236  						Type:        "string",
   237  						Mandatory:   false,
   238  						Aliases:     []config.Alias{{Name: "maven/projectSettingsFile"}},
   239  						Default:     os.Getenv("PIPER_projectSettingsFile"),
   240  					},
   241  					{
   242  						Name:        "globalSettingsFile",
   243  						ResourceRef: []config.ResourceReference{},
   244  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   245  						Type:        "string",
   246  						Mandatory:   false,
   247  						Aliases:     []config.Alias{{Name: "maven/globalSettingsFile"}},
   248  						Default:     os.Getenv("PIPER_globalSettingsFile"),
   249  					},
   250  					{
   251  						Name:        "m2Path",
   252  						ResourceRef: []config.ResourceReference{},
   253  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   254  						Type:        "string",
   255  						Mandatory:   false,
   256  						Aliases:     []config.Alias{{Name: "maven/m2Path"}},
   257  						Default:     os.Getenv("PIPER_m2Path"),
   258  					},
   259  					{
   260  						Name:        "logSuccessfulMavenTransfers",
   261  						ResourceRef: []config.ResourceReference{},
   262  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   263  						Type:        "bool",
   264  						Mandatory:   false,
   265  						Aliases:     []config.Alias{{Name: "maven/logSuccessfulMavenTransfers"}},
   266  						Default:     false,
   267  					},
   268  				},
   269  			},
   270  			Containers: []config.Container{
   271  				{Name: "mvn", Image: "maven:3.6-jdk-8"},
   272  			},
   273  			Sidecars: []config.Container{
   274  				{},
   275  			},
   276  			Outputs: config.StepOutputs{
   277  				Resources: []config.StepResources{
   278  					{
   279  						Name: "reports",
   280  						Type: "reports",
   281  						Parameters: []map[string]interface{}{
   282  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   283  							{"filePattern": "**/TEST-*.xml", "type": "junit"},
   284  							{"filePattern": "**/integration-test/*.xml", "type": "integration-test"},
   285  							{"filePattern": "**/jacoco.xml", "type": "jacoco-coverage"},
   286  						},
   287  					},
   288  				},
   289  			},
   290  		},
   291  	}
   292  	return theMetaData
   293  }