github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/tmsExport_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 tmsExportOptions struct {
    21  	TmsServiceKey            string                 `json:"tmsServiceKey,omitempty"`
    22  	CustomDescription        string                 `json:"customDescription,omitempty"`
    23  	NamedUser                string                 `json:"namedUser,omitempty"`
    24  	NodeName                 string                 `json:"nodeName,omitempty"`
    25  	MtaPath                  string                 `json:"mtaPath,omitempty"`
    26  	MtaVersion               string                 `json:"mtaVersion,omitempty"`
    27  	NodeExtDescriptorMapping map[string]interface{} `json:"nodeExtDescriptorMapping,omitempty"`
    28  	Proxy                    string                 `json:"proxy,omitempty"`
    29  }
    30  
    31  type tmsExportInflux struct {
    32  	step_data struct {
    33  		fields struct {
    34  			tms bool
    35  		}
    36  		tags struct {
    37  		}
    38  	}
    39  }
    40  
    41  func (i *tmsExportInflux) persist(path, resourceName string) {
    42  	measurementContent := []struct {
    43  		measurement string
    44  		valType     string
    45  		name        string
    46  		value       interface{}
    47  	}{
    48  		{valType: config.InfluxField, measurement: "step_data", name: "tms", value: i.step_data.fields.tms},
    49  	}
    50  
    51  	errCount := 0
    52  	for _, metric := range measurementContent {
    53  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value)
    54  		if err != nil {
    55  			log.Entry().WithError(err).Error("Error persisting influx environment.")
    56  			errCount++
    57  		}
    58  	}
    59  	if errCount > 0 {
    60  		log.Entry().Error("failed to persist Influx environment")
    61  	}
    62  }
    63  
    64  // TmsExportCommand This step allows you to export 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.
    65  func TmsExportCommand() *cobra.Command {
    66  	const STEP_NAME = "tmsExport"
    67  
    68  	metadata := tmsExportMetadata()
    69  	var stepConfig tmsExportOptions
    70  	var startTime time.Time
    71  	var influx tmsExportInflux
    72  	var logCollector *log.CollectorHook
    73  	var splunkClient *splunk.Splunk
    74  	telemetryClient := &telemetry.Telemetry{}
    75  
    76  	var createTmsExportCmd = &cobra.Command{
    77  		Use:   STEP_NAME,
    78  		Short: "This step allows you to export 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.",
    79  		Long: `This step allows you to export 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 to the import queues of the follow-on transport nodes of the specified export node.
    80  
    81  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.
    82  For more information, see [official documentation of SAP Cloud Transport Management service](https://help.sap.com/viewer/p/TRANSPORT_MANAGEMENT_SERVICE)
    83  
    84  !!! note "Prerequisites"
    85  * 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 your transport landscape.
    86  * 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 tmsServiceKey parameter.`,
    87  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    88  			startTime = time.Now()
    89  			log.SetStepName(STEP_NAME)
    90  			log.SetVerbose(GeneralConfig.Verbose)
    91  
    92  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    93  
    94  			path, _ := os.Getwd()
    95  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    96  			log.RegisterHook(fatalHook)
    97  
    98  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    99  			if err != nil {
   100  				log.SetErrorCategory(log.ErrorConfiguration)
   101  				return err
   102  			}
   103  			log.RegisterSecret(stepConfig.TmsServiceKey)
   104  
   105  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   106  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   107  				log.RegisterHook(&sentryHook)
   108  			}
   109  
   110  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   111  				splunkClient = &splunk.Splunk{}
   112  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   113  				log.RegisterHook(logCollector)
   114  			}
   115  
   116  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   117  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   118  			}
   119  
   120  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   121  			if err != nil {
   122  				return err
   123  			}
   124  			if err = validation.ValidateStruct(stepConfig); err != nil {
   125  				log.SetErrorCategory(log.ErrorConfiguration)
   126  				return err
   127  			}
   128  
   129  			return nil
   130  		},
   131  		Run: func(_ *cobra.Command, _ []string) {
   132  			stepTelemetryData := telemetry.CustomData{}
   133  			stepTelemetryData.ErrorCode = "1"
   134  			handler := func() {
   135  				influx.persist(GeneralConfig.EnvRootPath, "influx")
   136  				config.RemoveVaultSecretFiles()
   137  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   138  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   139  				stepTelemetryData.PiperCommitHash = GitCommit
   140  				telemetryClient.SetData(&stepTelemetryData)
   141  				telemetryClient.Send()
   142  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   143  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   144  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   145  						GeneralConfig.HookConfig.SplunkConfig.Token,
   146  						GeneralConfig.HookConfig.SplunkConfig.Index,
   147  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   148  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   149  				}
   150  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   151  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   152  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   153  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   154  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   155  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   156  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   157  				}
   158  			}
   159  			log.DeferExitHandler(handler)
   160  			defer handler()
   161  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   162  			tmsExport(stepConfig, &stepTelemetryData, &influx)
   163  			stepTelemetryData.ErrorCode = "0"
   164  			log.Entry().Info("SUCCESS")
   165  		},
   166  	}
   167  
   168  	addTmsExportFlags(createTmsExportCmd, &stepConfig)
   169  	return createTmsExportCmd
   170  }
   171  
   172  func addTmsExportFlags(cmd *cobra.Command, stepConfig *tmsExportOptions) {
   173  	cmd.Flags().StringVar(&stepConfig.TmsServiceKey, "tmsServiceKey", os.Getenv("PIPER_tmsServiceKey"), "Service key JSON string to access the SAP Cloud Transport Management service instance APIs. If not specified and if pipeline is running on Jenkins, service key, stored under ID provided with credentialsId parameter, is used.")
   174  	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.")
   175  	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.")
   176  	cmd.Flags().StringVar(&stepConfig.NodeName, "nodeName", os.Getenv("PIPER_nodeName"), "Defines the name of the export node - starting node in TMS landscape. The transport request is added to the queues of the follow-on nodes of export node.")
   177  	cmd.Flags().StringVar(&stepConfig.MtaPath, "mtaPath", os.Getenv("PIPER_mtaPath"), "Defines the relative path to *.mtar file for the export to the SAP Cloud Transport Management service. If not specified, it will use the *.mtar file created in mtaBuild.")
   178  	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.")
   179  
   180  	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.")
   181  
   182  	cmd.MarkFlagRequired("tmsServiceKey")
   183  	cmd.MarkFlagRequired("nodeName")
   184  }
   185  
   186  // retrieve step metadata
   187  func tmsExportMetadata() config.StepData {
   188  	var theMetaData = config.StepData{
   189  		Metadata: config.StepMetadata{
   190  			Name:        "tmsExport",
   191  			Aliases:     []config.Alias{},
   192  			Description: "This step allows you to export 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.",
   193  		},
   194  		Spec: config.StepSpec{
   195  			Inputs: config.StepInputs{
   196  				Secrets: []config.StepSecrets{
   197  					{Name: "credentialsId", Description: "Jenkins 'Secret text' credentials ID containing service key for SAP Cloud Transport Management service.", Type: "jenkins"},
   198  				},
   199  				Resources: []config.StepResources{
   200  					{Name: "buildResult", Type: "stash"},
   201  				},
   202  				Parameters: []config.StepParameters{
   203  					{
   204  						Name: "tmsServiceKey",
   205  						ResourceRef: []config.ResourceReference{
   206  							{
   207  								Name:  "credentialsId",
   208  								Param: "tmsServiceKey",
   209  								Type:  "secret",
   210  							},
   211  						},
   212  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   213  						Type:      "string",
   214  						Mandatory: true,
   215  						Aliases:   []config.Alias{},
   216  						Default:   os.Getenv("PIPER_tmsServiceKey"),
   217  					},
   218  					{
   219  						Name: "customDescription",
   220  						ResourceRef: []config.ResourceReference{
   221  							{
   222  								Name:  "commonPipelineEnvironment",
   223  								Param: "git/commitId",
   224  							},
   225  						},
   226  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   227  						Type:      "string",
   228  						Mandatory: false,
   229  						Aliases:   []config.Alias{},
   230  						Default:   os.Getenv("PIPER_customDescription"),
   231  					},
   232  					{
   233  						Name:        "namedUser",
   234  						ResourceRef: []config.ResourceReference{},
   235  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   236  						Type:        "string",
   237  						Mandatory:   false,
   238  						Aliases:     []config.Alias{},
   239  						Default:     `Piper-Pipeline`,
   240  					},
   241  					{
   242  						Name:        "nodeName",
   243  						ResourceRef: []config.ResourceReference{},
   244  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   245  						Type:        "string",
   246  						Mandatory:   true,
   247  						Aliases:     []config.Alias{},
   248  						Default:     os.Getenv("PIPER_nodeName"),
   249  					},
   250  					{
   251  						Name: "mtaPath",
   252  						ResourceRef: []config.ResourceReference{
   253  							{
   254  								Name:  "commonPipelineEnvironment",
   255  								Param: "mtarFilePath",
   256  							},
   257  						},
   258  						Scope:     []string{"PARAMETERS", "STEPS", "STAGES"},
   259  						Type:      "string",
   260  						Mandatory: false,
   261  						Aliases:   []config.Alias{},
   262  						Default:   os.Getenv("PIPER_mtaPath"),
   263  					},
   264  					{
   265  						Name:        "mtaVersion",
   266  						ResourceRef: []config.ResourceReference{},
   267  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   268  						Type:        "string",
   269  						Mandatory:   false,
   270  						Aliases:     []config.Alias{},
   271  						Default:     `*`,
   272  					},
   273  					{
   274  						Name:        "nodeExtDescriptorMapping",
   275  						ResourceRef: []config.ResourceReference{},
   276  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   277  						Type:        "map[string]interface{}",
   278  						Mandatory:   false,
   279  						Aliases:     []config.Alias{},
   280  					},
   281  					{
   282  						Name:        "proxy",
   283  						ResourceRef: []config.ResourceReference{},
   284  						Scope:       []string{"PARAMETERS", "STEPS", "STAGES"},
   285  						Type:        "string",
   286  						Mandatory:   false,
   287  						Aliases:     []config.Alias{},
   288  						Default:     os.Getenv("PIPER_proxy"),
   289  					},
   290  				},
   291  			},
   292  			Outputs: config.StepOutputs{
   293  				Resources: []config.StepResources{
   294  					{
   295  						Name: "influx",
   296  						Type: "influx",
   297  						Parameters: []map[string]interface{}{
   298  							{"name": "step_data", "fields": []map[string]string{{"name": "tms"}}},
   299  						},
   300  					},
   301  				},
   302  			},
   303  		},
   304  	}
   305  	return theMetaData
   306  }