github.com/jaylevin/jenkins-library@v1.230.4/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 {
   112  				splunkClient = &splunk.Splunk{}
   113  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   114  				log.RegisterHook(logCollector)
   115  			}
   116  
   117  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   118  			if err != nil {
   119  				return err
   120  			}
   121  			if err = validation.ValidateStruct(stepConfig); err != nil {
   122  				log.SetErrorCategory(log.ErrorConfiguration)
   123  				return err
   124  			}
   125  
   126  			return nil
   127  		},
   128  		Run: func(_ *cobra.Command, _ []string) {
   129  			stepTelemetryData := telemetry.CustomData{}
   130  			stepTelemetryData.ErrorCode = "1"
   131  			handler := func() {
   132  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   133  				config.RemoveVaultSecretFiles()
   134  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   135  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   136  				stepTelemetryData.PiperCommitHash = GitCommit
   137  				telemetryClient.SetData(&stepTelemetryData)
   138  				telemetryClient.Send()
   139  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   140  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   141  				}
   142  			}
   143  			log.DeferExitHandler(handler)
   144  			defer handler()
   145  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   146  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   147  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   148  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   149  					GeneralConfig.HookConfig.SplunkConfig.Token,
   150  					GeneralConfig.HookConfig.SplunkConfig.Index,
   151  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   152  			}
   153  			mavenExecuteIntegration(stepConfig, &stepTelemetryData)
   154  			stepTelemetryData.ErrorCode = "0"
   155  			log.Entry().Info("SUCCESS")
   156  		},
   157  	}
   158  
   159  	addMavenExecuteIntegrationFlags(createMavenExecuteIntegrationCmd, &stepConfig)
   160  	return createMavenExecuteIntegrationCmd
   161  }
   162  
   163  func addMavenExecuteIntegrationFlags(cmd *cobra.Command, stepConfig *mavenExecuteIntegrationOptions) {
   164  	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.")
   165  	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.")
   166  	cmd.Flags().StringVar(&stepConfig.Goal, "goal", `test`, "The name of the Maven goal to execute.")
   167  	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.")
   168  	cmd.Flags().StringVar(&stepConfig.ProjectSettingsFile, "projectSettingsFile", os.Getenv("PIPER_projectSettingsFile"), "Path to the mvn settings file that should be used as project settings file.")
   169  	cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
   170  	cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "Path to the location of the local repository that should be used.")
   171  	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.")
   172  
   173  }
   174  
   175  // retrieve step metadata
   176  func mavenExecuteIntegrationMetadata() config.StepData {
   177  	var theMetaData = config.StepData{
   178  		Metadata: config.StepMetadata{
   179  			Name:        "mavenExecuteIntegration",
   180  			Aliases:     []config.Alias{{Name: "mavenExecute", Deprecated: false}},
   181  			Description: "This step will execute backend integration tests via the Jacoco Maven-plugin.",
   182  		},
   183  		Spec: config.StepSpec{
   184  			Inputs: config.StepInputs{
   185  				Parameters: []config.StepParameters{
   186  					{
   187  						Name:        "retry",
   188  						ResourceRef: []config.ResourceReference{},
   189  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   190  						Type:        "int",
   191  						Mandatory:   false,
   192  						Aliases:     []config.Alias{},
   193  						Default:     1,
   194  					},
   195  					{
   196  						Name:        "forkCount",
   197  						ResourceRef: []config.ResourceReference{},
   198  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   199  						Type:        "string",
   200  						Mandatory:   false,
   201  						Aliases:     []config.Alias{},
   202  						Default:     `1C`,
   203  					},
   204  					{
   205  						Name:        "goal",
   206  						ResourceRef: []config.ResourceReference{},
   207  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   208  						Type:        "string",
   209  						Mandatory:   false,
   210  						Aliases:     []config.Alias{},
   211  						Default:     `test`,
   212  					},
   213  					{
   214  						Name:        "installArtifacts",
   215  						ResourceRef: []config.ResourceReference{},
   216  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   217  						Type:        "bool",
   218  						Mandatory:   false,
   219  						Aliases:     []config.Alias{},
   220  						Default:     true,
   221  					},
   222  					{
   223  						Name:        "projectSettingsFile",
   224  						ResourceRef: []config.ResourceReference{},
   225  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   226  						Type:        "string",
   227  						Mandatory:   false,
   228  						Aliases:     []config.Alias{{Name: "maven/projectSettingsFile"}},
   229  						Default:     os.Getenv("PIPER_projectSettingsFile"),
   230  					},
   231  					{
   232  						Name:        "globalSettingsFile",
   233  						ResourceRef: []config.ResourceReference{},
   234  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   235  						Type:        "string",
   236  						Mandatory:   false,
   237  						Aliases:     []config.Alias{{Name: "maven/globalSettingsFile"}},
   238  						Default:     os.Getenv("PIPER_globalSettingsFile"),
   239  					},
   240  					{
   241  						Name:        "m2Path",
   242  						ResourceRef: []config.ResourceReference{},
   243  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   244  						Type:        "string",
   245  						Mandatory:   false,
   246  						Aliases:     []config.Alias{{Name: "maven/m2Path"}},
   247  						Default:     os.Getenv("PIPER_m2Path"),
   248  					},
   249  					{
   250  						Name:        "logSuccessfulMavenTransfers",
   251  						ResourceRef: []config.ResourceReference{},
   252  						Scope:       []string{"GENERAL", "STEPS", "STAGES", "PARAMETERS"},
   253  						Type:        "bool",
   254  						Mandatory:   false,
   255  						Aliases:     []config.Alias{{Name: "maven/logSuccessfulMavenTransfers"}},
   256  						Default:     false,
   257  					},
   258  				},
   259  			},
   260  			Containers: []config.Container{
   261  				{Name: "mvn", Image: "maven:3.6-jdk-8"},
   262  			},
   263  			Sidecars: []config.Container{
   264  				{},
   265  			},
   266  			Outputs: config.StepOutputs{
   267  				Resources: []config.StepResources{
   268  					{
   269  						Name: "reports",
   270  						Type: "reports",
   271  						Parameters: []map[string]interface{}{
   272  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   273  							{"filePattern": "**/TEST-*.xml", "type": "junit"},
   274  							{"filePattern": "**/integration-test/*.xml", "type": "integration-test"},
   275  							{"filePattern": "**/jacoco.xml", "type": "jacoco-coverage"},
   276  						},
   277  					},
   278  				},
   279  			},
   280  		},
   281  	}
   282  	return theMetaData
   283  }