github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/transportRequestUploadSOLMAN_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 transportRequestUploadSOLMANOptions struct {
    21  	Endpoint           string   `json:"endpoint,omitempty"`
    22  	Username           string   `json:"username,omitempty"`
    23  	Password           string   `json:"password,omitempty"`
    24  	ApplicationID      string   `json:"applicationId,omitempty"`
    25  	ChangeDocumentID   string   `json:"changeDocumentId,omitempty"`
    26  	TransportRequestID string   `json:"transportRequestId,omitempty"`
    27  	FilePath           string   `json:"filePath,omitempty"`
    28  	CmClientOpts       []string `json:"cmClientOpts,omitempty"`
    29  }
    30  
    31  type transportRequestUploadSOLMANCommonPipelineEnvironment struct {
    32  	custom struct {
    33  		changeDocumentID   string
    34  		transportRequestID string
    35  	}
    36  }
    37  
    38  func (p *transportRequestUploadSOLMANCommonPipelineEnvironment) persist(path, resourceName string) {
    39  	content := []struct {
    40  		category string
    41  		name     string
    42  		value    interface{}
    43  	}{
    44  		{category: "custom", name: "changeDocumentId", value: p.custom.changeDocumentID},
    45  		{category: "custom", name: "transportRequestId", value: p.custom.transportRequestID},
    46  	}
    47  
    48  	errCount := 0
    49  	for _, param := range content {
    50  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
    51  		if err != nil {
    52  			log.Entry().WithError(err).Error("Error persisting piper environment.")
    53  			errCount++
    54  		}
    55  	}
    56  	if errCount > 0 {
    57  		log.Entry().Error("failed to persist Piper environment")
    58  	}
    59  }
    60  
    61  // TransportRequestUploadSOLMANCommand Uploads a specified file into a given transport via Solution Manager
    62  func TransportRequestUploadSOLMANCommand() *cobra.Command {
    63  	const STEP_NAME = "transportRequestUploadSOLMAN"
    64  
    65  	metadata := transportRequestUploadSOLMANMetadata()
    66  	var stepConfig transportRequestUploadSOLMANOptions
    67  	var startTime time.Time
    68  	var commonPipelineEnvironment transportRequestUploadSOLMANCommonPipelineEnvironment
    69  	var logCollector *log.CollectorHook
    70  	var splunkClient *splunk.Splunk
    71  	telemetryClient := &telemetry.Telemetry{}
    72  
    73  	var createTransportRequestUploadSOLMANCmd = &cobra.Command{
    74  		Use:   STEP_NAME,
    75  		Short: "Uploads a specified file into a given transport via Solution Manager",
    76  		Long: `Uploads the specified file into the given transport request via Solution Manager.
    77  The mandatory change document ID points to the associate change document item.
    78  The application ID specifies how the file needs to be handled on server side.`,
    79  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    80  			startTime = time.Now()
    81  			log.SetStepName(STEP_NAME)
    82  			log.SetVerbose(GeneralConfig.Verbose)
    83  
    84  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    85  
    86  			path, _ := os.Getwd()
    87  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    88  			log.RegisterHook(fatalHook)
    89  
    90  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    91  			if err != nil {
    92  				log.SetErrorCategory(log.ErrorConfiguration)
    93  				return err
    94  			}
    95  			log.RegisterSecret(stepConfig.Username)
    96  			log.RegisterSecret(stepConfig.Password)
    97  
    98  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    99  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   100  				log.RegisterHook(&sentryHook)
   101  			}
   102  
   103  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   104  				splunkClient = &splunk.Splunk{}
   105  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   106  				log.RegisterHook(logCollector)
   107  			}
   108  
   109  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   110  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   111  			}
   112  
   113  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   114  			if err != nil {
   115  				return err
   116  			}
   117  			if err = validation.ValidateStruct(stepConfig); err != nil {
   118  				log.SetErrorCategory(log.ErrorConfiguration)
   119  				return err
   120  			}
   121  
   122  			return nil
   123  		},
   124  		Run: func(_ *cobra.Command, _ []string) {
   125  			stepTelemetryData := telemetry.CustomData{}
   126  			stepTelemetryData.ErrorCode = "1"
   127  			handler := func() {
   128  				commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
   129  				config.RemoveVaultSecretFiles()
   130  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   131  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   132  				stepTelemetryData.PiperCommitHash = GitCommit
   133  				telemetryClient.SetData(&stepTelemetryData)
   134  				telemetryClient.Send()
   135  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   136  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   137  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   138  						GeneralConfig.HookConfig.SplunkConfig.Token,
   139  						GeneralConfig.HookConfig.SplunkConfig.Index,
   140  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   141  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   142  				}
   143  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   144  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   145  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   146  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   147  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   148  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   149  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   150  				}
   151  			}
   152  			log.DeferExitHandler(handler)
   153  			defer handler()
   154  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   155  			transportRequestUploadSOLMAN(stepConfig, &stepTelemetryData, &commonPipelineEnvironment)
   156  			stepTelemetryData.ErrorCode = "0"
   157  			log.Entry().Info("SUCCESS")
   158  		},
   159  	}
   160  
   161  	addTransportRequestUploadSOLMANFlags(createTransportRequestUploadSOLMANCmd, &stepConfig)
   162  	return createTransportRequestUploadSOLMANCmd
   163  }
   164  
   165  func addTransportRequestUploadSOLMANFlags(cmd *cobra.Command, stepConfig *transportRequestUploadSOLMANOptions) {
   166  	cmd.Flags().StringVar(&stepConfig.Endpoint, "endpoint", os.Getenv("PIPER_endpoint"), "Service endpoint")
   167  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "Service user for uploading to the Solution Manager")
   168  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Service user password for uploading to the Solution Manager")
   169  	cmd.Flags().StringVar(&stepConfig.ApplicationID, "applicationId", os.Getenv("PIPER_applicationId"), "Id of the application. Specifies how the file needs to be handled on server side")
   170  	cmd.Flags().StringVar(&stepConfig.ChangeDocumentID, "changeDocumentId", os.Getenv("PIPER_changeDocumentId"), "ID of the change document to which the file is uploaded")
   171  	cmd.Flags().StringVar(&stepConfig.TransportRequestID, "transportRequestId", os.Getenv("PIPER_transportRequestId"), "ID of the transport request to which the file is uploaded")
   172  	cmd.Flags().StringVar(&stepConfig.FilePath, "filePath", os.Getenv("PIPER_filePath"), "Name/Path of the file which should be uploaded")
   173  	cmd.Flags().StringSliceVar(&stepConfig.CmClientOpts, "cmClientOpts", []string{}, "Additional options handed over to the cm client")
   174  
   175  	cmd.MarkFlagRequired("endpoint")
   176  	cmd.MarkFlagRequired("username")
   177  	cmd.MarkFlagRequired("password")
   178  	cmd.MarkFlagRequired("applicationId")
   179  	cmd.MarkFlagRequired("changeDocumentId")
   180  	cmd.MarkFlagRequired("transportRequestId")
   181  	cmd.MarkFlagRequired("filePath")
   182  	cmd.MarkFlagRequired("cmClientOpts")
   183  }
   184  
   185  // retrieve step metadata
   186  func transportRequestUploadSOLMANMetadata() config.StepData {
   187  	var theMetaData = config.StepData{
   188  		Metadata: config.StepMetadata{
   189  			Name:        "transportRequestUploadSOLMAN",
   190  			Aliases:     []config.Alias{{Name: "transportRequestUploadFile", Deprecated: false}},
   191  			Description: "Uploads a specified file into a given transport via Solution Manager",
   192  		},
   193  		Spec: config.StepSpec{
   194  			Inputs: config.StepInputs{
   195  				Secrets: []config.StepSecrets{
   196  					{Name: "uploadCredentialsId", Description: "Jenkins 'Username with password' credentials ID containing user and password to authenticate against the ABAP backend", Type: "jenkins", Aliases: []config.Alias{{Name: "changeManagement/credentialsId", Deprecated: false}}},
   197  				},
   198  				Parameters: []config.StepParameters{
   199  					{
   200  						Name:        "endpoint",
   201  						ResourceRef: []config.ResourceReference{},
   202  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   203  						Type:        "string",
   204  						Mandatory:   true,
   205  						Aliases:     []config.Alias{{Name: "changeManagement/endpoint"}},
   206  						Default:     os.Getenv("PIPER_endpoint"),
   207  					},
   208  					{
   209  						Name: "username",
   210  						ResourceRef: []config.ResourceReference{
   211  							{
   212  								Name:  "uploadCredentialsId",
   213  								Param: "username",
   214  								Type:  "secret",
   215  							},
   216  						},
   217  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   218  						Type:      "string",
   219  						Mandatory: true,
   220  						Aliases:   []config.Alias{},
   221  						Default:   os.Getenv("PIPER_username"),
   222  					},
   223  					{
   224  						Name: "password",
   225  						ResourceRef: []config.ResourceReference{
   226  							{
   227  								Name:  "uploadCredentialsId",
   228  								Param: "password",
   229  								Type:  "secret",
   230  							},
   231  						},
   232  						Scope:     []string{"PARAMETERS"},
   233  						Type:      "string",
   234  						Mandatory: true,
   235  						Aliases:   []config.Alias{},
   236  						Default:   os.Getenv("PIPER_password"),
   237  					},
   238  					{
   239  						Name:        "applicationId",
   240  						ResourceRef: []config.ResourceReference{},
   241  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   242  						Type:        "string",
   243  						Mandatory:   true,
   244  						Aliases:     []config.Alias{},
   245  						Default:     os.Getenv("PIPER_applicationId"),
   246  					},
   247  					{
   248  						Name: "changeDocumentId",
   249  						ResourceRef: []config.ResourceReference{
   250  							{
   251  								Name:  "commonPipelineEnvironment",
   252  								Param: "custom/changeDocumentId",
   253  							},
   254  						},
   255  						Scope:     []string{"PARAMETERS"},
   256  						Type:      "string",
   257  						Mandatory: true,
   258  						Aliases:   []config.Alias{},
   259  						Default:   os.Getenv("PIPER_changeDocumentId"),
   260  					},
   261  					{
   262  						Name: "transportRequestId",
   263  						ResourceRef: []config.ResourceReference{
   264  							{
   265  								Name:  "commonPipelineEnvironment",
   266  								Param: "custom/transportRequestId",
   267  							},
   268  						},
   269  						Scope:     []string{"PARAMETERS"},
   270  						Type:      "string",
   271  						Mandatory: true,
   272  						Aliases:   []config.Alias{},
   273  						Default:   os.Getenv("PIPER_transportRequestId"),
   274  					},
   275  					{
   276  						Name: "filePath",
   277  						ResourceRef: []config.ResourceReference{
   278  							{
   279  								Name:  "commonPipelineEnvironment",
   280  								Param: "mtarFilePath",
   281  							},
   282  						},
   283  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   284  						Type:      "string",
   285  						Mandatory: true,
   286  						Aliases:   []config.Alias{},
   287  						Default:   os.Getenv("PIPER_filePath"),
   288  					},
   289  					{
   290  						Name:        "cmClientOpts",
   291  						ResourceRef: []config.ResourceReference{},
   292  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
   293  						Type:        "[]string",
   294  						Mandatory:   true,
   295  						Aliases:     []config.Alias{{Name: "clientOpts"}, {Name: "changeManagement/clientOpts"}},
   296  						Default:     []string{},
   297  					},
   298  				},
   299  			},
   300  			Containers: []config.Container{
   301  				{Name: "cmclient", Image: "ppiper/cm-client:3.0.0.0"},
   302  			},
   303  			Outputs: config.StepOutputs{
   304  				Resources: []config.StepResources{
   305  					{
   306  						Name: "commonPipelineEnvironment",
   307  						Type: "piperEnvironment",
   308  						Parameters: []map[string]interface{}{
   309  							{"name": "custom/changeDocumentId"},
   310  							{"name": "custom/transportRequestId"},
   311  						},
   312  					},
   313  				},
   314  			},
   315  		},
   316  	}
   317  	return theMetaData
   318  }