github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/integrationArtifactTriggerIntegrationTest_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  	"path/filepath"
     9  	"time"
    10  
    11  	"github.com/SAP/jenkins-library/pkg/config"
    12  	"github.com/SAP/jenkins-library/pkg/log"
    13  	"github.com/SAP/jenkins-library/pkg/piperenv"
    14  	"github.com/SAP/jenkins-library/pkg/splunk"
    15  	"github.com/SAP/jenkins-library/pkg/telemetry"
    16  	"github.com/SAP/jenkins-library/pkg/validation"
    17  	"github.com/spf13/cobra"
    18  )
    19  
    20  type integrationArtifactTriggerIntegrationTestOptions struct {
    21  	IntegrationFlowServiceKey         string `json:"integrationFlowServiceKey,omitempty"`
    22  	IntegrationFlowID                 string `json:"integrationFlowId,omitempty"`
    23  	IntegrationFlowServiceEndpointURL string `json:"integrationFlowServiceEndpointUrl,omitempty"`
    24  	ContentType                       string `json:"contentType,omitempty"`
    25  	MessageBodyPath                   string `json:"messageBodyPath,omitempty"`
    26  }
    27  
    28  type integrationArtifactTriggerIntegrationTestCommonPipelineEnvironment struct {
    29  	custom struct {
    30  		integrationFlowTriggerIntegrationTestResponseBody    string
    31  		integrationFlowTriggerIntegrationTestResponseHeaders string
    32  	}
    33  }
    34  
    35  func (p *integrationArtifactTriggerIntegrationTestCommonPipelineEnvironment) persist(path, resourceName string) {
    36  	content := []struct {
    37  		category string
    38  		name     string
    39  		value    interface{}
    40  	}{
    41  		{category: "custom", name: "integrationFlowTriggerIntegrationTestResponseBody", value: p.custom.integrationFlowTriggerIntegrationTestResponseBody},
    42  		{category: "custom", name: "integrationFlowTriggerIntegrationTestResponseHeaders", value: p.custom.integrationFlowTriggerIntegrationTestResponseHeaders},
    43  	}
    44  
    45  	errCount := 0
    46  	for _, param := range content {
    47  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
    48  		if err != nil {
    49  			log.Entry().WithError(err).Error("Error persisting piper environment.")
    50  			errCount++
    51  		}
    52  	}
    53  	if errCount > 0 {
    54  		log.Entry().Error("failed to persist Piper environment")
    55  	}
    56  }
    57  
    58  // IntegrationArtifactTriggerIntegrationTestCommand Test the service endpoint of your iFlow
    59  func IntegrationArtifactTriggerIntegrationTestCommand() *cobra.Command {
    60  	const STEP_NAME = "integrationArtifactTriggerIntegrationTest"
    61  
    62  	metadata := integrationArtifactTriggerIntegrationTestMetadata()
    63  	var stepConfig integrationArtifactTriggerIntegrationTestOptions
    64  	var startTime time.Time
    65  	var commonPipelineEnvironment integrationArtifactTriggerIntegrationTestCommonPipelineEnvironment
    66  	var logCollector *log.CollectorHook
    67  	var splunkClient *splunk.Splunk
    68  	telemetryClient := &telemetry.Telemetry{}
    69  
    70  	var createIntegrationArtifactTriggerIntegrationTestCmd = &cobra.Command{
    71  		Use:   STEP_NAME,
    72  		Short: "Test the service endpoint of your iFlow",
    73  		Long:  `With this step you can test your intergration flow  exposed by SAP BTP Integration on a tenant using OData API.Learn more about the SAP Cloud Integration remote API for getting service endpoint of deployed integration artifact [here](https://help.sap.com/viewer/368c481cd6954bdfa5d0435479fd4eaf/Cloud/en-US/d1679a80543f46509a7329243b595bdb.html).`,
    74  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    75  			startTime = time.Now()
    76  			log.SetStepName(STEP_NAME)
    77  			log.SetVerbose(GeneralConfig.Verbose)
    78  
    79  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    80  
    81  			path, _ := os.Getwd()
    82  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    83  			log.RegisterHook(fatalHook)
    84  
    85  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    86  			if err != nil {
    87  				log.SetErrorCategory(log.ErrorConfiguration)
    88  				return err
    89  			}
    90  			log.RegisterSecret(stepConfig.IntegrationFlowServiceKey)
    91  
    92  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    93  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    94  				log.RegisterHook(&sentryHook)
    95  			}
    96  
    97  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    98  				splunkClient = &splunk.Splunk{}
    99  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   100  				log.RegisterHook(logCollector)
   101  			}
   102  
   103  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   104  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   105  			}
   106  
   107  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   108  			if err != nil {
   109  				return err
   110  			}
   111  			if err = validation.ValidateStruct(stepConfig); err != nil {
   112  				log.SetErrorCategory(log.ErrorConfiguration)
   113  				return err
   114  			}
   115  
   116  			return nil
   117  		},
   118  		Run: func(_ *cobra.Command, _ []string) {
   119  			stepTelemetryData := telemetry.CustomData{}
   120  			stepTelemetryData.ErrorCode = "1"
   121  			handler := func() {
   122  				commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
   123  				config.RemoveVaultSecretFiles()
   124  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   125  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   126  				stepTelemetryData.PiperCommitHash = GitCommit
   127  				telemetryClient.SetData(&stepTelemetryData)
   128  				telemetryClient.Send()
   129  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   130  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   131  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   132  						GeneralConfig.HookConfig.SplunkConfig.Token,
   133  						GeneralConfig.HookConfig.SplunkConfig.Index,
   134  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   135  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   136  				}
   137  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   138  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   139  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   140  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   141  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   142  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   143  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   144  				}
   145  			}
   146  			log.DeferExitHandler(handler)
   147  			defer handler()
   148  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   149  			integrationArtifactTriggerIntegrationTest(stepConfig, &stepTelemetryData, &commonPipelineEnvironment)
   150  			stepTelemetryData.ErrorCode = "0"
   151  			log.Entry().Info("SUCCESS")
   152  		},
   153  	}
   154  
   155  	addIntegrationArtifactTriggerIntegrationTestFlags(createIntegrationArtifactTriggerIntegrationTestCmd, &stepConfig)
   156  	return createIntegrationArtifactTriggerIntegrationTestCmd
   157  }
   158  
   159  func addIntegrationArtifactTriggerIntegrationTestFlags(cmd *cobra.Command, stepConfig *integrationArtifactTriggerIntegrationTestOptions) {
   160  	cmd.Flags().StringVar(&stepConfig.IntegrationFlowServiceKey, "integrationFlowServiceKey", os.Getenv("PIPER_integrationFlowServiceKey"), "Service key JSON string to access the Process Integration Runtime service instance of plan 'integration-flow'")
   161  	cmd.Flags().StringVar(&stepConfig.IntegrationFlowID, "integrationFlowId", os.Getenv("PIPER_integrationFlowId"), "Specifies the ID of the Integration Flow artifact")
   162  	cmd.Flags().StringVar(&stepConfig.IntegrationFlowServiceEndpointURL, "integrationFlowServiceEndpointUrl", os.Getenv("PIPER_integrationFlowServiceEndpointUrl"), "Specifies the URL endpoint of the iFlow. Please provide in the format `<protocol>://<host>:<port>`. Supported protocols are `http` and `https`.")
   163  	cmd.Flags().StringVar(&stepConfig.ContentType, "contentType", os.Getenv("PIPER_contentType"), "Specifies the content type of the file defined in messageBodyPath e.g. application/json")
   164  	cmd.Flags().StringVar(&stepConfig.MessageBodyPath, "messageBodyPath", os.Getenv("PIPER_messageBodyPath"), "Speficfies the relative file path to the message body.")
   165  
   166  	cmd.MarkFlagRequired("integrationFlowServiceKey")
   167  	cmd.MarkFlagRequired("integrationFlowId")
   168  	cmd.MarkFlagRequired("integrationFlowServiceEndpointUrl")
   169  }
   170  
   171  // retrieve step metadata
   172  func integrationArtifactTriggerIntegrationTestMetadata() config.StepData {
   173  	var theMetaData = config.StepData{
   174  		Metadata: config.StepMetadata{
   175  			Name:        "integrationArtifactTriggerIntegrationTest",
   176  			Aliases:     []config.Alias{},
   177  			Description: "Test the service endpoint of your iFlow",
   178  		},
   179  		Spec: config.StepSpec{
   180  			Inputs: config.StepInputs{
   181  				Secrets: []config.StepSecrets{
   182  					{Name: "integrationFlowServiceKeyCredentialsId", Description: "Jenkins secret text credential ID containing the service key to the Process Integration Runtime service instance of plan 'integration-flow'", Type: "jenkins"},
   183  				},
   184  				Parameters: []config.StepParameters{
   185  					{
   186  						Name: "integrationFlowServiceKey",
   187  						ResourceRef: []config.ResourceReference{
   188  							{
   189  								Name:  "integrationFlowServiceKeyCredentialsId",
   190  								Param: "integrationFlowServiceKey",
   191  								Type:  "secret",
   192  							},
   193  						},
   194  						Scope:     []string{"PARAMETERS"},
   195  						Type:      "string",
   196  						Mandatory: true,
   197  						Aliases:   []config.Alias{},
   198  						Default:   os.Getenv("PIPER_integrationFlowServiceKey"),
   199  					},
   200  					{
   201  						Name:        "integrationFlowId",
   202  						ResourceRef: []config.ResourceReference{},
   203  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   204  						Type:        "string",
   205  						Mandatory:   true,
   206  						Aliases:     []config.Alias{},
   207  						Default:     os.Getenv("PIPER_integrationFlowId"),
   208  					},
   209  					{
   210  						Name: "integrationFlowServiceEndpointUrl",
   211  						ResourceRef: []config.ResourceReference{
   212  							{
   213  								Name:  "commonPipelineEnvironment",
   214  								Param: "custom/integrationFlowServiceEndpoint",
   215  							},
   216  						},
   217  						Scope:     []string{"PARAMETERS"},
   218  						Type:      "string",
   219  						Mandatory: true,
   220  						Aliases:   []config.Alias{},
   221  						Default:   os.Getenv("PIPER_integrationFlowServiceEndpointUrl"),
   222  					},
   223  					{
   224  						Name:        "contentType",
   225  						ResourceRef: []config.ResourceReference{},
   226  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   227  						Type:        "string",
   228  						Mandatory:   false,
   229  						Aliases:     []config.Alias{},
   230  						Default:     os.Getenv("PIPER_contentType"),
   231  					},
   232  					{
   233  						Name:        "messageBodyPath",
   234  						ResourceRef: []config.ResourceReference{},
   235  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   236  						Type:        "string",
   237  						Mandatory:   false,
   238  						Aliases:     []config.Alias{},
   239  						Default:     os.Getenv("PIPER_messageBodyPath"),
   240  					},
   241  				},
   242  			},
   243  			Outputs: config.StepOutputs{
   244  				Resources: []config.StepResources{
   245  					{
   246  						Name: "commonPipelineEnvironment",
   247  						Type: "piperEnvironment",
   248  						Parameters: []map[string]interface{}{
   249  							{"name": "custom/integrationFlowTriggerIntegrationTestResponseBody"},
   250  							{"name": "custom/integrationFlowTriggerIntegrationTestResponseHeaders"},
   251  						},
   252  					},
   253  				},
   254  			},
   255  		},
   256  	}
   257  	return theMetaData
   258  }