github.com/SAP/jenkins-library@v1.362.0/cmd/containerExecuteStructureTests_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 containerExecuteStructureTestsOptions struct {
    19  	PullImage          bool   `json:"pullImage,omitempty"`
    20  	TestConfiguration  string `json:"testConfiguration,omitempty"`
    21  	TestDriver         string `json:"testDriver,omitempty"`
    22  	TestImage          string `json:"testImage,omitempty"`
    23  	TestReportFilePath string `json:"testReportFilePath,omitempty"`
    24  }
    25  
    26  // ContainerExecuteStructureTestsCommand In this step [Container Structure Tests](https://github.com/GoogleContainerTools/container-structure-test) are executed.
    27  func ContainerExecuteStructureTestsCommand() *cobra.Command {
    28  	const STEP_NAME = "containerExecuteStructureTests"
    29  
    30  	metadata := containerExecuteStructureTestsMetadata()
    31  	var stepConfig containerExecuteStructureTestsOptions
    32  	var startTime time.Time
    33  	var logCollector *log.CollectorHook
    34  	var splunkClient *splunk.Splunk
    35  	telemetryClient := &telemetry.Telemetry{}
    36  
    37  	var createContainerExecuteStructureTestsCmd = &cobra.Command{
    38  		Use:   STEP_NAME,
    39  		Short: "In this step [Container Structure Tests](https://github.com/GoogleContainerTools/container-structure-test) are executed.",
    40  		Long: `This testing framework allows you to execute different test types against a Docker container, for example:
    41  - Command tests (only if a Docker Deamon is available)
    42  - File existence tests
    43  - File content tests
    44  - Metadata test`,
    45  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    46  			startTime = time.Now()
    47  			log.SetStepName(STEP_NAME)
    48  			log.SetVerbose(GeneralConfig.Verbose)
    49  
    50  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    51  
    52  			path, _ := os.Getwd()
    53  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    54  			log.RegisterHook(fatalHook)
    55  
    56  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    57  			if err != nil {
    58  				log.SetErrorCategory(log.ErrorConfiguration)
    59  				return err
    60  			}
    61  
    62  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    63  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    64  				log.RegisterHook(&sentryHook)
    65  			}
    66  
    67  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
    68  				splunkClient = &splunk.Splunk{}
    69  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    70  				log.RegisterHook(logCollector)
    71  			}
    72  
    73  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    74  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    75  			}
    76  
    77  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    78  			if err != nil {
    79  				return err
    80  			}
    81  			if err = validation.ValidateStruct(stepConfig); err != nil {
    82  				log.SetErrorCategory(log.ErrorConfiguration)
    83  				return err
    84  			}
    85  
    86  			return nil
    87  		},
    88  		Run: func(_ *cobra.Command, _ []string) {
    89  			stepTelemetryData := telemetry.CustomData{}
    90  			stepTelemetryData.ErrorCode = "1"
    91  			handler := func() {
    92  				config.RemoveVaultSecretFiles()
    93  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    94  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    95  				stepTelemetryData.PiperCommitHash = GitCommit
    96  				telemetryClient.SetData(&stepTelemetryData)
    97  				telemetryClient.Send()
    98  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    99  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   100  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   101  						GeneralConfig.HookConfig.SplunkConfig.Token,
   102  						GeneralConfig.HookConfig.SplunkConfig.Index,
   103  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   104  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   105  				}
   106  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   107  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   108  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   109  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   110  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   111  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   112  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   113  				}
   114  			}
   115  			log.DeferExitHandler(handler)
   116  			defer handler()
   117  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   118  			containerExecuteStructureTests(stepConfig, &stepTelemetryData)
   119  			stepTelemetryData.ErrorCode = "0"
   120  			log.Entry().Info("SUCCESS")
   121  		},
   122  	}
   123  
   124  	addContainerExecuteStructureTestsFlags(createContainerExecuteStructureTestsCmd, &stepConfig)
   125  	return createContainerExecuteStructureTestsCmd
   126  }
   127  
   128  func addContainerExecuteStructureTestsFlags(cmd *cobra.Command, stepConfig *containerExecuteStructureTestsOptions) {
   129  	cmd.Flags().BoolVar(&stepConfig.PullImage, "pullImage", false, "Force a pull of the tested image before running tests. Only relevant for testDriver 'docker'.")
   130  	cmd.Flags().StringVar(&stepConfig.TestConfiguration, "testConfiguration", os.Getenv("PIPER_testConfiguration"), "Container structure test configuration in yml or json format. You can pass a pattern in order to execute multiple tests.")
   131  	cmd.Flags().StringVar(&stepConfig.TestDriver, "testDriver", os.Getenv("PIPER_testDriver"), "Container structure test driver to be used for testing, please see https://github.com/GoogleContainerTools/container-structure-test for details.")
   132  	cmd.Flags().StringVar(&stepConfig.TestImage, "testImage", os.Getenv("PIPER_testImage"), "Image to be tested")
   133  	cmd.Flags().StringVar(&stepConfig.TestReportFilePath, "testReportFilePath", `cst-report.json`, "Path and name of the test report which will be generated")
   134  
   135  	cmd.MarkFlagRequired("testConfiguration")
   136  	cmd.MarkFlagRequired("testImage")
   137  }
   138  
   139  // retrieve step metadata
   140  func containerExecuteStructureTestsMetadata() config.StepData {
   141  	var theMetaData = config.StepData{
   142  		Metadata: config.StepMetadata{
   143  			Name:        "containerExecuteStructureTests",
   144  			Aliases:     []config.Alias{},
   145  			Description: "In this step [Container Structure Tests](https://github.com/GoogleContainerTools/container-structure-test) are executed.",
   146  		},
   147  		Spec: config.StepSpec{
   148  			Inputs: config.StepInputs{
   149  				Parameters: []config.StepParameters{
   150  					{
   151  						Name:        "pullImage",
   152  						ResourceRef: []config.ResourceReference{},
   153  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   154  						Type:        "bool",
   155  						Mandatory:   false,
   156  						Aliases:     []config.Alias{},
   157  						Default:     false,
   158  					},
   159  					{
   160  						Name:        "testConfiguration",
   161  						ResourceRef: []config.ResourceReference{},
   162  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   163  						Type:        "string",
   164  						Mandatory:   true,
   165  						Aliases:     []config.Alias{},
   166  						Default:     os.Getenv("PIPER_testConfiguration"),
   167  					},
   168  					{
   169  						Name:        "testDriver",
   170  						ResourceRef: []config.ResourceReference{},
   171  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   172  						Type:        "string",
   173  						Mandatory:   false,
   174  						Aliases:     []config.Alias{},
   175  						Default:     os.Getenv("PIPER_testDriver"),
   176  					},
   177  					{
   178  						Name:        "testImage",
   179  						ResourceRef: []config.ResourceReference{},
   180  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   181  						Type:        "string",
   182  						Mandatory:   true,
   183  						Aliases:     []config.Alias{},
   184  						Default:     os.Getenv("PIPER_testImage"),
   185  					},
   186  					{
   187  						Name:        "testReportFilePath",
   188  						ResourceRef: []config.ResourceReference{},
   189  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   190  						Type:        "string",
   191  						Mandatory:   false,
   192  						Aliases:     []config.Alias{},
   193  						Default:     `cst-report.json`,
   194  					},
   195  				},
   196  			},
   197  			Containers: []config.Container{
   198  				{Image: "gcr.io/gcp-runtimes/container-structure-test:debug", Options: []config.Option{{Name: "-u", Value: "0"}, {Name: "--entrypoint", Value: ""}}},
   199  			},
   200  		},
   201  	}
   202  	return theMetaData
   203  }