github.com/SAP/jenkins-library@v1.362.0/cmd/containerSaveImage_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 containerSaveImageOptions struct {
    19  	ContainerRegistryURL      string `json:"containerRegistryUrl,omitempty"`
    20  	ContainerImage            string `json:"containerImage,omitempty"`
    21  	ContainerRegistryPassword string `json:"containerRegistryPassword,omitempty"`
    22  	ContainerRegistryUser     string `json:"containerRegistryUser,omitempty"`
    23  	FilePath                  string `json:"filePath,omitempty"`
    24  	DockerConfigJSON          string `json:"dockerConfigJSON,omitempty"`
    25  	ImageFormat               string `json:"imageFormat,omitempty" validate:"possible-values=tarball oci legacy"`
    26  }
    27  
    28  // ContainerSaveImageCommand Saves a container image as a tar file
    29  func ContainerSaveImageCommand() *cobra.Command {
    30  	const STEP_NAME = "containerSaveImage"
    31  
    32  	metadata := containerSaveImageMetadata()
    33  	var stepConfig containerSaveImageOptions
    34  	var startTime time.Time
    35  	var logCollector *log.CollectorHook
    36  	var splunkClient *splunk.Splunk
    37  	telemetryClient := &telemetry.Telemetry{}
    38  
    39  	var createContainerSaveImageCmd = &cobra.Command{
    40  		Use:   STEP_NAME,
    41  		Short: "Saves a container image as a tar file",
    42  		Long: `This step allows you to save a container image, for example a Docker image into a tar file.
    43  
    44  It can be used no matter if a Docker daemon is available or not. It will also work inside a Kubernetes cluster without access to a daemon.`,
    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  			log.RegisterSecret(stepConfig.ContainerRegistryPassword)
    62  			log.RegisterSecret(stepConfig.ContainerRegistryUser)
    63  			log.RegisterSecret(stepConfig.DockerConfigJSON)
    64  
    65  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    66  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    67  				log.RegisterHook(&sentryHook)
    68  			}
    69  
    70  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
    71  				splunkClient = &splunk.Splunk{}
    72  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    73  				log.RegisterHook(logCollector)
    74  			}
    75  
    76  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    77  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    78  			}
    79  
    80  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    81  			if err != nil {
    82  				return err
    83  			}
    84  			if err = validation.ValidateStruct(stepConfig); err != nil {
    85  				log.SetErrorCategory(log.ErrorConfiguration)
    86  				return err
    87  			}
    88  
    89  			return nil
    90  		},
    91  		Run: func(_ *cobra.Command, _ []string) {
    92  			stepTelemetryData := telemetry.CustomData{}
    93  			stepTelemetryData.ErrorCode = "1"
    94  			handler := func() {
    95  				config.RemoveVaultSecretFiles()
    96  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    97  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    98  				stepTelemetryData.PiperCommitHash = GitCommit
    99  				telemetryClient.SetData(&stepTelemetryData)
   100  				telemetryClient.Send()
   101  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   102  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   103  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   104  						GeneralConfig.HookConfig.SplunkConfig.Token,
   105  						GeneralConfig.HookConfig.SplunkConfig.Index,
   106  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   107  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   108  				}
   109  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   110  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   111  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   112  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   113  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   114  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   115  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   116  				}
   117  			}
   118  			log.DeferExitHandler(handler)
   119  			defer handler()
   120  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   121  			containerSaveImage(stepConfig, &stepTelemetryData)
   122  			stepTelemetryData.ErrorCode = "0"
   123  			log.Entry().Info("SUCCESS")
   124  		},
   125  	}
   126  
   127  	addContainerSaveImageFlags(createContainerSaveImageCmd, &stepConfig)
   128  	return createContainerSaveImageCmd
   129  }
   130  
   131  func addContainerSaveImageFlags(cmd *cobra.Command, stepConfig *containerSaveImageOptions) {
   132  	cmd.Flags().StringVar(&stepConfig.ContainerRegistryURL, "containerRegistryUrl", os.Getenv("PIPER_containerRegistryUrl"), "For `buildTool: docker`: Url of the container registry - typically provided by the CI/CD environment.")
   133  	cmd.Flags().StringVar(&stepConfig.ContainerImage, "containerImage", os.Getenv("PIPER_containerImage"), "Container image to be saved.")
   134  	cmd.Flags().StringVar(&stepConfig.ContainerRegistryPassword, "containerRegistryPassword", os.Getenv("PIPER_containerRegistryPassword"), "For `buildTool: docker`: Password for container registry access - typically provided by the CI/CD environment.")
   135  	cmd.Flags().StringVar(&stepConfig.ContainerRegistryUser, "containerRegistryUser", os.Getenv("PIPER_containerRegistryUser"), "For `buildTool: docker`: Username for container registry access - typically provided by the CI/CD environment.")
   136  	cmd.Flags().StringVar(&stepConfig.FilePath, "filePath", os.Getenv("PIPER_filePath"), "The path to the file to which the image should be saved.")
   137  	cmd.Flags().StringVar(&stepConfig.DockerConfigJSON, "dockerConfigJSON", os.Getenv("PIPER_dockerConfigJSON"), "Path to the file `.docker/config.json` - this is typically provided by your CI/CD system. You can find more details about the Docker credentials in the [Docker documentation](https://docs.docker.com/engine/reference/commandline/login/).")
   138  	cmd.Flags().StringVar(&stepConfig.ImageFormat, "imageFormat", `legacy`, "Format of the image when saving the docker image locally.")
   139  
   140  	cmd.MarkFlagRequired("containerRegistryUrl")
   141  	cmd.MarkFlagRequired("containerImage")
   142  }
   143  
   144  // retrieve step metadata
   145  func containerSaveImageMetadata() config.StepData {
   146  	var theMetaData = config.StepData{
   147  		Metadata: config.StepMetadata{
   148  			Name:        "containerSaveImage",
   149  			Aliases:     []config.Alias{},
   150  			Description: "Saves a container image as a tar file",
   151  		},
   152  		Spec: config.StepSpec{
   153  			Inputs: config.StepInputs{
   154  				Secrets: []config.StepSecrets{
   155  					{Name: "dockerConfigJsonCredentialsId", Description: "Jenkins 'Secret file' credentials ID containing Docker config.json (with registry credential(s)). You can find more details about the Docker credentials in the [Docker documentation](https://docs.docker.com/engine/reference/commandline/login/).", Type: "jenkins", Aliases: []config.Alias{{Name: "dockerCredentialsId", Deprecated: true}}},
   156  				},
   157  				Parameters: []config.StepParameters{
   158  					{
   159  						Name: "containerRegistryUrl",
   160  						ResourceRef: []config.ResourceReference{
   161  							{
   162  								Name:  "commonPipelineEnvironment",
   163  								Param: "container/registryUrl",
   164  							},
   165  						},
   166  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   167  						Type:      "string",
   168  						Mandatory: true,
   169  						Aliases:   []config.Alias{{Name: "dockerRegistryUrl"}},
   170  						Default:   os.Getenv("PIPER_containerRegistryUrl"),
   171  					},
   172  					{
   173  						Name: "containerImage",
   174  						ResourceRef: []config.ResourceReference{
   175  							{
   176  								Name:  "commonPipelineEnvironment",
   177  								Param: "container/imageNameTag",
   178  							},
   179  						},
   180  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   181  						Type:      "string",
   182  						Mandatory: true,
   183  						Aliases:   []config.Alias{{Name: "dockerImage"}, {Name: "scanImage"}},
   184  						Default:   os.Getenv("PIPER_containerImage"),
   185  					},
   186  					{
   187  						Name: "containerRegistryPassword",
   188  						ResourceRef: []config.ResourceReference{
   189  							{
   190  								Name:  "commonPipelineEnvironment",
   191  								Param: "container/repositoryPassword",
   192  							},
   193  
   194  							{
   195  								Name:  "commonPipelineEnvironment",
   196  								Param: "custom/repositoryPassword",
   197  							},
   198  						},
   199  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   200  						Type:      "string",
   201  						Mandatory: false,
   202  						Aliases:   []config.Alias{},
   203  						Default:   os.Getenv("PIPER_containerRegistryPassword"),
   204  					},
   205  					{
   206  						Name: "containerRegistryUser",
   207  						ResourceRef: []config.ResourceReference{
   208  							{
   209  								Name:  "commonPipelineEnvironment",
   210  								Param: "container/repositoryUsername",
   211  							},
   212  
   213  							{
   214  								Name:  "commonPipelineEnvironment",
   215  								Param: "custom/repositoryUsername",
   216  							},
   217  						},
   218  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   219  						Type:      "string",
   220  						Mandatory: false,
   221  						Aliases:   []config.Alias{},
   222  						Default:   os.Getenv("PIPER_containerRegistryUser"),
   223  					},
   224  					{
   225  						Name:        "filePath",
   226  						ResourceRef: []config.ResourceReference{},
   227  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   228  						Type:        "string",
   229  						Mandatory:   false,
   230  						Aliases:     []config.Alias{},
   231  						Default:     os.Getenv("PIPER_filePath"),
   232  					},
   233  					{
   234  						Name: "dockerConfigJSON",
   235  						ResourceRef: []config.ResourceReference{
   236  							{
   237  								Name:  "commonPipelineEnvironment",
   238  								Param: "custom/dockerConfigJSON",
   239  							},
   240  
   241  							{
   242  								Name: "dockerConfigJsonCredentialsId",
   243  								Type: "secret",
   244  							},
   245  
   246  							{
   247  								Name:    "dockerConfigFileVaultSecretName",
   248  								Type:    "vaultSecretFile",
   249  								Default: "docker-config",
   250  							},
   251  						},
   252  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   253  						Type:      "string",
   254  						Mandatory: false,
   255  						Aliases:   []config.Alias{},
   256  						Default:   os.Getenv("PIPER_dockerConfigJSON"),
   257  					},
   258  					{
   259  						Name:        "imageFormat",
   260  						ResourceRef: []config.ResourceReference{},
   261  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   262  						Type:        "string",
   263  						Mandatory:   false,
   264  						Aliases:     []config.Alias{},
   265  						Default:     `legacy`,
   266  					},
   267  				},
   268  			},
   269  		},
   270  	}
   271  	return theMetaData
   272  }