github.com/SAP/jenkins-library@v1.362.0/cmd/tmsUpload_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 tmsUploadOptions struct {
    21  	TmsServiceKey            string                 `json:"tmsServiceKey,omitempty"`
    22  	ServiceKey               string                 `json:"serviceKey,omitempty"`
    23  	CustomDescription        string                 `json:"customDescription,omitempty"`
    24  	NamedUser                string                 `json:"namedUser,omitempty"`
    25  	NodeName                 string                 `json:"nodeName,omitempty"`
    26  	MtaPath                  string                 `json:"mtaPath,omitempty"`
    27  	MtaVersion               string                 `json:"mtaVersion,omitempty"`
    28  	NodeExtDescriptorMapping map[string]interface{} `json:"nodeExtDescriptorMapping,omitempty"`
    29  	Proxy                    string                 `json:"proxy,omitempty"`
    30  	StashContent             []string               `json:"stashContent,omitempty"`
    31  }
    32  
    33  type tmsUploadInflux struct {
    34  	step_data struct {
    35  		fields struct {
    36  			tms bool
    37  		}
    38  		tags struct {
    39  		}
    40  	}
    41  }
    42  
    43  func (i *tmsUploadInflux) persist(path, resourceName string) {
    44  	measurementContent := []struct {
    45  		measurement string
    46  		valType     string
    47  		name        string
    48  		value       interface{}
    49  	}{
    50  		{valType: config.InfluxField, measurement: "step_data", name: "tms", value: i.step_data.fields.tms},
    51  	}
    52  
    53  	errCount := 0
    54  	for _, metric := range measurementContent {
    55  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value)
    56  		if err != nil {
    57  			log.Entry().WithError(err).Error("Error persisting influx environment.")
    58  			errCount++
    59  		}
    60  	}
    61  	if errCount > 0 {
    62  		log.Entry().Error("failed to persist Influx environment")
    63  	}
    64  }
    65  
    66  // TmsUploadCommand This step allows you to upload an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) landscape for further TMS-controlled distribution through a TMS-configured landscape.
    67  func TmsUploadCommand() *cobra.Command {
    68  	const STEP_NAME = "tmsUpload"
    69  
    70  	metadata := tmsUploadMetadata()
    71  	var stepConfig tmsUploadOptions
    72  	var startTime time.Time
    73  	var influx tmsUploadInflux
    74  	var logCollector *log.CollectorHook
    75  	var splunkClient *splunk.Splunk
    76  	telemetryClient := &telemetry.Telemetry{}
    77  
    78  	var createTmsUploadCmd = &cobra.Command{
    79  		Use:   STEP_NAME,
    80  		Short: "This step allows you to upload an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) landscape for further TMS-controlled distribution through a TMS-configured landscape.",
    81  		Long: `This step allows you to upload an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) landscape for further TMS-controlled distribution through a TMS-configured landscape. The MTA file is attached to a new transport request which is added directly to the import queue of the specified transport node.
    82  
    83  TMS lets you manage transports between SAP Business Technology Platform accounts in Neo and Cloud Foundry, such as from DEV to TEST and PROD accounts.
    84  For more information, see [official documentation of SAP Cloud Transport Management service](https://help.sap.com/viewer/p/TRANSPORT_MANAGEMENT_SERVICE)
    85  
    86  !!! note "Prerequisites"
    87  * You have subscribed to and set up TMS, as described in [Initial Setup](https://help.sap.com/viewer/7f7160ec0d8546c6b3eab72fb5ad6fd8/Cloud/en-US/66fd7283c62f48adb23c56fb48c84a60.html), which includes the configuration of a node to be used for uploading an MTA file.
    88  * A corresponding service key has been created, as described in [Set Up the Environment to Transport Content Archives directly in an Application](https://help.sap.com/viewer/7f7160ec0d8546c6b3eab72fb5ad6fd8/Cloud/en-US/8d9490792ed14f1bbf8a6ac08a6bca64.html). This service key (JSON) must be stored as a secret text within the Jenkins secure store or provided as value of serviceKey parameter.`,
    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  			log.RegisterSecret(stepConfig.TmsServiceKey)
   106  			log.RegisterSecret(stepConfig.ServiceKey)
   107  
   108  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   109  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   110  				log.RegisterHook(&sentryHook)
   111  			}
   112  
   113  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   114  				splunkClient = &splunk.Splunk{}
   115  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   116  				log.RegisterHook(logCollector)
   117  			}
   118  
   119  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   120  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   121  			}
   122  
   123  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   124  			if err != nil {
   125  				return err
   126  			}
   127  			if err = validation.ValidateStruct(stepConfig); err != nil {
   128  				log.SetErrorCategory(log.ErrorConfiguration)
   129  				return err
   130  			}
   131  
   132  			return nil
   133  		},
   134  		Run: func(_ *cobra.Command, _ []string) {
   135  			stepTelemetryData := telemetry.CustomData{}
   136  			stepTelemetryData.ErrorCode = "1"
   137  			handler := func() {
   138  				influx.persist(GeneralConfig.EnvRootPath, "influx")
   139  				config.RemoveVaultSecretFiles()
   140  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   141  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   142  				stepTelemetryData.PiperCommitHash = GitCommit
   143  				telemetryClient.SetData(&stepTelemetryData)
   144  				telemetryClient.Send()
   145  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   146  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   147  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   148  						GeneralConfig.HookConfig.SplunkConfig.Token,
   149  						GeneralConfig.HookConfig.SplunkConfig.Index,
   150  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   151  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   152  				}
   153  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   154  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   155  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   156  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   157  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   158  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   159  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   160  				}
   161  			}
   162  			log.DeferExitHandler(handler)
   163  			defer handler()
   164  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   165  			tmsUpload(stepConfig, &stepTelemetryData, &influx)
   166  			stepTelemetryData.ErrorCode = "0"
   167  			log.Entry().Info("SUCCESS")
   168  		},
   169  	}
   170  
   171  	addTmsUploadFlags(createTmsUploadCmd, &stepConfig)
   172  	return createTmsUploadCmd
   173  }
   174  
   175  func addTmsUploadFlags(cmd *cobra.Command, stepConfig *tmsUploadOptions) {
   176  	cmd.Flags().StringVar(&stepConfig.TmsServiceKey, "tmsServiceKey", os.Getenv("PIPER_tmsServiceKey"), "DEPRECATION WARNING: This parameter has been deprecated, please use the serviceKey parameter instead, which supports both service key for TMS (SAP Cloud Transport Management service), as well as service key for CALM (SAP Cloud Application Lifecycle Management) service.\nService key JSON string to access the SAP Cloud Transport Management service instance APIs.\n")
   177  	cmd.Flags().StringVar(&stepConfig.ServiceKey, "serviceKey", os.Getenv("PIPER_serviceKey"), "Service key JSON string to access TMS (SAP Cloud Transport Management service) instance APIs. This can be a service key for TMS, or a service key for CALM (SAP Cloud Application Lifecycle Management) service. If not specified and if pipeline is running on Jenkins, service key, stored under ID provided with credentialsId parameter, is used.\n")
   178  	cmd.Flags().StringVar(&stepConfig.CustomDescription, "customDescription", os.Getenv("PIPER_customDescription"), "Can be used as the description of a transport request. Will overwrite the default, which is corresponding Git commit ID.")
   179  	cmd.Flags().StringVar(&stepConfig.NamedUser, "namedUser", `Piper-Pipeline`, "Defines the named user to execute transport request with. The default value is 'Piper-Pipeline'. If pipeline is running on Jenkins, the name of the user, who started the job, is tried to be used at first.")
   180  	cmd.Flags().StringVar(&stepConfig.NodeName, "nodeName", os.Getenv("PIPER_nodeName"), "Defines the name of the node to which the *.mtar file should be uploaded.")
   181  	cmd.Flags().StringVar(&stepConfig.MtaPath, "mtaPath", os.Getenv("PIPER_mtaPath"), "Defines the relative path to *.mtar file for the upload to the SAP Cloud Transport Management service. If not specified, it will use the *.mtar file created in mtaBuild.")
   182  	cmd.Flags().StringVar(&stepConfig.MtaVersion, "mtaVersion", `*`, "Defines the version of the MTA for which the MTA extension descriptor will be used. You can use an asterisk (*) to accept any MTA version, or use a specific version compliant with SemVer 2.0, e.g. 1.0.0 (see semver.org). If the parameter is not configured, an asterisk is used.")
   183  
   184  	cmd.Flags().StringVar(&stepConfig.Proxy, "proxy", os.Getenv("PIPER_proxy"), "Proxy URL which should be used for communication with the SAP Cloud Transport Management service backend.")
   185  	cmd.Flags().StringSliceVar(&stepConfig.StashContent, "stashContent", []string{`buildResult`}, "If specific stashes should be considered during Jenkins execution, their names need to be passed as a list via this parameter, e.g. stashContent: [\"deployDescriptor\", \"buildResult\"]. By default, the build result is considered.")
   186  
   187  	cmd.MarkFlagRequired("serviceKey")
   188  	cmd.MarkFlagRequired("nodeName")
   189  }
   190  
   191  // retrieve step metadata
   192  func tmsUploadMetadata() config.StepData {
   193  	var theMetaData = config.StepData{
   194  		Metadata: config.StepMetadata{
   195  			Name:        "tmsUpload",
   196  			Aliases:     []config.Alias{},
   197  			Description: "This step allows you to upload an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) landscape for further TMS-controlled distribution through a TMS-configured landscape.",
   198  		},
   199  		Spec: config.StepSpec{
   200  			Inputs: config.StepInputs{
   201  				Secrets: []config.StepSecrets{
   202  					{Name: "credentialsId", Description: "Jenkins 'Secret text' credentials ID containing service key for TMS (SAP Cloud Transport Management service) or CALM (SAP Cloud Application Lifecycle Management) service.", Type: "jenkins"},
   203  				},
   204  				Resources: []config.StepResources{
   205  					{Name: "buildResult", Type: "stash"},
   206  				},
   207  				Parameters: []config.StepParameters{
   208  					{
   209  						Name:        "tmsServiceKey",
   210  						ResourceRef: []config.ResourceReference{},
   211  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   212  						Type:        "string",
   213  						Mandatory:   false,
   214  						Aliases:     []config.Alias{},
   215  						Default:     os.Getenv("PIPER_tmsServiceKey"),
   216  					},
   217  					{
   218  						Name: "serviceKey",
   219  						ResourceRef: []config.ResourceReference{
   220  							{
   221  								Name:  "credentialsId",
   222  								Param: "serviceKey",
   223  								Type:  "secret",
   224  							},
   225  						},
   226  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   227  						Type:      "string",
   228  						Mandatory: true,
   229  						Aliases:   []config.Alias{},
   230  						Default:   os.Getenv("PIPER_serviceKey"),
   231  					},
   232  					{
   233  						Name: "customDescription",
   234  						ResourceRef: []config.ResourceReference{
   235  							{
   236  								Name:  "commonPipelineEnvironment",
   237  								Param: "git/commitId",
   238  							},
   239  						},
   240  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   241  						Type:      "string",
   242  						Mandatory: false,
   243  						Aliases:   []config.Alias{},
   244  						Default:   os.Getenv("PIPER_customDescription"),
   245  					},
   246  					{
   247  						Name:        "namedUser",
   248  						ResourceRef: []config.ResourceReference{},
   249  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   250  						Type:        "string",
   251  						Mandatory:   false,
   252  						Aliases:     []config.Alias{},
   253  						Default:     `Piper-Pipeline`,
   254  					},
   255  					{
   256  						Name:        "nodeName",
   257  						ResourceRef: []config.ResourceReference{},
   258  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   259  						Type:        "string",
   260  						Mandatory:   true,
   261  						Aliases:     []config.Alias{},
   262  						Default:     os.Getenv("PIPER_nodeName"),
   263  					},
   264  					{
   265  						Name: "mtaPath",
   266  						ResourceRef: []config.ResourceReference{
   267  							{
   268  								Name:  "commonPipelineEnvironment",
   269  								Param: "mtarFilePath",
   270  							},
   271  						},
   272  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   273  						Type:      "string",
   274  						Mandatory: false,
   275  						Aliases:   []config.Alias{},
   276  						Default:   os.Getenv("PIPER_mtaPath"),
   277  					},
   278  					{
   279  						Name:        "mtaVersion",
   280  						ResourceRef: []config.ResourceReference{},
   281  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   282  						Type:        "string",
   283  						Mandatory:   false,
   284  						Aliases:     []config.Alias{},
   285  						Default:     `*`,
   286  					},
   287  					{
   288  						Name:        "nodeExtDescriptorMapping",
   289  						ResourceRef: []config.ResourceReference{},
   290  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   291  						Type:        "map[string]interface{}",
   292  						Mandatory:   false,
   293  						Aliases:     []config.Alias{},
   294  					},
   295  					{
   296  						Name:        "proxy",
   297  						ResourceRef: []config.ResourceReference{},
   298  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   299  						Type:        "string",
   300  						Mandatory:   false,
   301  						Aliases:     []config.Alias{},
   302  						Default:     os.Getenv("PIPER_proxy"),
   303  					},
   304  					{
   305  						Name:        "stashContent",
   306  						ResourceRef: []config.ResourceReference{},
   307  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   308  						Type:        "[]string",
   309  						Mandatory:   false,
   310  						Aliases:     []config.Alias{},
   311  						Default:     []string{`buildResult`},
   312  					},
   313  				},
   314  			},
   315  			Outputs: config.StepOutputs{
   316  				Resources: []config.StepResources{
   317  					{
   318  						Name: "influx",
   319  						Type: "influx",
   320  						Parameters: []map[string]interface{}{
   321  							{"name": "step_data", "fields": []map[string]string{{"name": "tms"}}},
   322  						},
   323  					},
   324  				},
   325  			},
   326  		},
   327  	}
   328  	return theMetaData
   329  }