github.com/SAP/jenkins-library@v1.362.0/cmd/ansSendEvent_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  	"time"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/config"
    11  	"github.com/SAP/jenkins-library/pkg/log"
    12  	"github.com/SAP/jenkins-library/pkg/splunk"
    13  	"github.com/SAP/jenkins-library/pkg/telemetry"
    14  	"github.com/SAP/jenkins-library/pkg/validation"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type ansSendEventOptions struct {
    19  	AnsServiceKey    string                 `json:"ansServiceKey,omitempty"`
    20  	EventType        string                 `json:"eventType,omitempty"`
    21  	Severity         string                 `json:"severity,omitempty" validate:"possible-values=INFO NOTICE WARNING ERROR FATAL"`
    22  	Category         string                 `json:"category,omitempty" validate:"possible-values=NOTIFICATION ALERT EXCEPTION"`
    23  	Subject          string                 `json:"subject,omitempty"`
    24  	Body             string                 `json:"body,omitempty"`
    25  	Priority         int                    `json:"priority,omitempty"`
    26  	Tags             map[string]interface{} `json:"tags,omitempty"`
    27  	ResourceName     string                 `json:"resourceName,omitempty"`
    28  	ResourceType     string                 `json:"resourceType,omitempty"`
    29  	ResourceInstance string                 `json:"resourceInstance,omitempty"`
    30  	ResourceTags     map[string]interface{} `json:"resourceTags,omitempty"`
    31  }
    32  
    33  // AnsSendEventCommand Send Event to the SAP Alert Notification Service
    34  func AnsSendEventCommand() *cobra.Command {
    35  	const STEP_NAME = "ansSendEvent"
    36  
    37  	metadata := ansSendEventMetadata()
    38  	var stepConfig ansSendEventOptions
    39  	var startTime time.Time
    40  	var logCollector *log.CollectorHook
    41  	var splunkClient *splunk.Splunk
    42  	telemetryClient := &telemetry.Telemetry{}
    43  
    44  	var createAnsSendEventCmd = &cobra.Command{
    45  		Use:   STEP_NAME,
    46  		Short: "Send Event to the SAP Alert Notification Service",
    47  		Long:  `With this step one can send an Event to the SAP Alert Notification Service.`,
    48  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    49  			startTime = time.Now()
    50  			log.SetStepName(STEP_NAME)
    51  			log.SetVerbose(GeneralConfig.Verbose)
    52  
    53  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    54  
    55  			path, _ := os.Getwd()
    56  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    57  			log.RegisterHook(fatalHook)
    58  
    59  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    60  			if err != nil {
    61  				log.SetErrorCategory(log.ErrorConfiguration)
    62  				return err
    63  			}
    64  			log.RegisterSecret(stepConfig.AnsServiceKey)
    65  
    66  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    67  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    68  				log.RegisterHook(&sentryHook)
    69  			}
    70  
    71  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
    72  				splunkClient = &splunk.Splunk{}
    73  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    74  				log.RegisterHook(logCollector)
    75  			}
    76  
    77  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    78  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    79  			}
    80  
    81  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    82  			if err != nil {
    83  				return err
    84  			}
    85  			if err = validation.ValidateStruct(stepConfig); err != nil {
    86  				log.SetErrorCategory(log.ErrorConfiguration)
    87  				return err
    88  			}
    89  
    90  			return nil
    91  		},
    92  		Run: func(_ *cobra.Command, _ []string) {
    93  			stepTelemetryData := telemetry.CustomData{}
    94  			stepTelemetryData.ErrorCode = "1"
    95  			handler := func() {
    96  				config.RemoveVaultSecretFiles()
    97  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    98  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    99  				stepTelemetryData.PiperCommitHash = GitCommit
   100  				telemetryClient.SetData(&stepTelemetryData)
   101  				telemetryClient.Send()
   102  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   103  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   104  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   105  						GeneralConfig.HookConfig.SplunkConfig.Token,
   106  						GeneralConfig.HookConfig.SplunkConfig.Index,
   107  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   108  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   109  				}
   110  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   111  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   112  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   113  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   114  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   115  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   116  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   117  				}
   118  			}
   119  			log.DeferExitHandler(handler)
   120  			defer handler()
   121  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   122  			ansSendEvent(stepConfig, &stepTelemetryData)
   123  			stepTelemetryData.ErrorCode = "0"
   124  			log.Entry().Info("SUCCESS")
   125  		},
   126  	}
   127  
   128  	addAnsSendEventFlags(createAnsSendEventCmd, &stepConfig)
   129  	return createAnsSendEventCmd
   130  }
   131  
   132  func addAnsSendEventFlags(cmd *cobra.Command, stepConfig *ansSendEventOptions) {
   133  	cmd.Flags().StringVar(&stepConfig.AnsServiceKey, "ansServiceKey", os.Getenv("PIPER_ansServiceKey"), "Service key JSON string to access the SAP Alert Notification Service")
   134  	cmd.Flags().StringVar(&stepConfig.EventType, "eventType", `Piper`, "Type of the event")
   135  	cmd.Flags().StringVar(&stepConfig.Severity, "severity", `INFO`, "Event severity")
   136  	cmd.Flags().StringVar(&stepConfig.Category, "category", `NOTIFICATION`, "Event category")
   137  	cmd.Flags().StringVar(&stepConfig.Subject, "subject", `ansSendEvent`, "Short description of the event")
   138  	cmd.Flags().StringVar(&stepConfig.Body, "body", `Call from Piper step ansSendEvent`, "Detailed description of the event")
   139  	cmd.Flags().IntVar(&stepConfig.Priority, "priority", 0, "Event priority in the range of 1 to 1000")
   140  
   141  	cmd.Flags().StringVar(&stepConfig.ResourceName, "resourceName", `Pipeline`, "Unique resource name")
   142  	cmd.Flags().StringVar(&stepConfig.ResourceType, "resourceType", `Pipeline`, "Resource type identifier")
   143  	cmd.Flags().StringVar(&stepConfig.ResourceInstance, "resourceInstance", os.Getenv("PIPER_resourceInstance"), "Optional resource instance identifier")
   144  
   145  	cmd.MarkFlagRequired("ansServiceKey")
   146  }
   147  
   148  // retrieve step metadata
   149  func ansSendEventMetadata() config.StepData {
   150  	var theMetaData = config.StepData{
   151  		Metadata: config.StepMetadata{
   152  			Name:        "ansSendEvent",
   153  			Aliases:     []config.Alias{},
   154  			Description: "Send Event to the SAP Alert Notification Service",
   155  		},
   156  		Spec: config.StepSpec{
   157  			Inputs: config.StepInputs{
   158  				Secrets: []config.StepSecrets{
   159  					{Name: "ansServiceKeyCredentialsId", Description: "Jenkins secret text credential ID containing the service key to access the SAP Alert Notification Service", Type: "jenkins"},
   160  				},
   161  				Parameters: []config.StepParameters{
   162  					{
   163  						Name: "ansServiceKey",
   164  						ResourceRef: []config.ResourceReference{
   165  							{
   166  								Name:  "ansServiceKeyCredentialsId",
   167  								Param: "ansServiceKey",
   168  								Type:  "secret",
   169  							},
   170  						},
   171  						Scope:     []string{"PARAMETERS"},
   172  						Type:      "string",
   173  						Mandatory: true,
   174  						Aliases:   []config.Alias{},
   175  						Default:   os.Getenv("PIPER_ansServiceKey"),
   176  					},
   177  					{
   178  						Name:        "eventType",
   179  						ResourceRef: []config.ResourceReference{},
   180  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   181  						Type:        "string",
   182  						Mandatory:   false,
   183  						Aliases:     []config.Alias{},
   184  						Default:     `Piper`,
   185  					},
   186  					{
   187  						Name:        "severity",
   188  						ResourceRef: []config.ResourceReference{},
   189  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   190  						Type:        "string",
   191  						Mandatory:   false,
   192  						Aliases:     []config.Alias{},
   193  						Default:     `INFO`,
   194  					},
   195  					{
   196  						Name:        "category",
   197  						ResourceRef: []config.ResourceReference{},
   198  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   199  						Type:        "string",
   200  						Mandatory:   false,
   201  						Aliases:     []config.Alias{},
   202  						Default:     `NOTIFICATION`,
   203  					},
   204  					{
   205  						Name:        "subject",
   206  						ResourceRef: []config.ResourceReference{},
   207  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   208  						Type:        "string",
   209  						Mandatory:   false,
   210  						Aliases:     []config.Alias{},
   211  						Default:     `ansSendEvent`,
   212  					},
   213  					{
   214  						Name:        "body",
   215  						ResourceRef: []config.ResourceReference{},
   216  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   217  						Type:        "string",
   218  						Mandatory:   false,
   219  						Aliases:     []config.Alias{},
   220  						Default:     `Call from Piper step ansSendEvent`,
   221  					},
   222  					{
   223  						Name:        "priority",
   224  						ResourceRef: []config.ResourceReference{},
   225  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   226  						Type:        "int",
   227  						Mandatory:   false,
   228  						Aliases:     []config.Alias{},
   229  						Default:     0,
   230  					},
   231  					{
   232  						Name:        "tags",
   233  						ResourceRef: []config.ResourceReference{},
   234  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   235  						Type:        "map[string]interface{}",
   236  						Mandatory:   false,
   237  						Aliases:     []config.Alias{},
   238  					},
   239  					{
   240  						Name:        "resourceName",
   241  						ResourceRef: []config.ResourceReference{},
   242  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   243  						Type:        "string",
   244  						Mandatory:   false,
   245  						Aliases:     []config.Alias{},
   246  						Default:     `Pipeline`,
   247  					},
   248  					{
   249  						Name:        "resourceType",
   250  						ResourceRef: []config.ResourceReference{},
   251  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   252  						Type:        "string",
   253  						Mandatory:   false,
   254  						Aliases:     []config.Alias{},
   255  						Default:     `Pipeline`,
   256  					},
   257  					{
   258  						Name:        "resourceInstance",
   259  						ResourceRef: []config.ResourceReference{},
   260  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   261  						Type:        "string",
   262  						Mandatory:   false,
   263  						Aliases:     []config.Alias{},
   264  						Default:     os.Getenv("PIPER_resourceInstance"),
   265  					},
   266  					{
   267  						Name:        "resourceTags",
   268  						ResourceRef: []config.ResourceReference{},
   269  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   270  						Type:        "map[string]interface{}",
   271  						Mandatory:   false,
   272  						Aliases:     []config.Alias{},
   273  					},
   274  				},
   275  			},
   276  		},
   277  	}
   278  	return theMetaData
   279  }