github.com/jaylevin/jenkins-library@v1.230.4/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 {
    71  				splunkClient = &splunk.Splunk{}
    72  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    73  				log.RegisterHook(logCollector)
    74  			}
    75  
    76  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    77  			if err != nil {
    78  				return err
    79  			}
    80  			if err = validation.ValidateStruct(stepConfig); err != nil {
    81  				log.SetErrorCategory(log.ErrorConfiguration)
    82  				return err
    83  			}
    84  
    85  			return nil
    86  		},
    87  		Run: func(_ *cobra.Command, _ []string) {
    88  			stepTelemetryData := telemetry.CustomData{}
    89  			stepTelemetryData.ErrorCode = "1"
    90  			handler := func() {
    91  				config.RemoveVaultSecretFiles()
    92  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
    93  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
    94  				stepTelemetryData.PiperCommitHash = GitCommit
    95  				telemetryClient.SetData(&stepTelemetryData)
    96  				telemetryClient.Send()
    97  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    98  					splunkClient.Send(telemetryClient.GetData(), logCollector)
    99  				}
   100  			}
   101  			log.DeferExitHandler(handler)
   102  			defer handler()
   103  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   104  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   105  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   106  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   107  					GeneralConfig.HookConfig.SplunkConfig.Token,
   108  					GeneralConfig.HookConfig.SplunkConfig.Index,
   109  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   110  			}
   111  			containerSaveImage(stepConfig, &stepTelemetryData)
   112  			stepTelemetryData.ErrorCode = "0"
   113  			log.Entry().Info("SUCCESS")
   114  		},
   115  	}
   116  
   117  	addContainerSaveImageFlags(createContainerSaveImageCmd, &stepConfig)
   118  	return createContainerSaveImageCmd
   119  }
   120  
   121  func addContainerSaveImageFlags(cmd *cobra.Command, stepConfig *containerSaveImageOptions) {
   122  	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.")
   123  	cmd.Flags().StringVar(&stepConfig.ContainerImage, "containerImage", os.Getenv("PIPER_containerImage"), "Container image to be saved.")
   124  	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.")
   125  	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.")
   126  	cmd.Flags().StringVar(&stepConfig.FilePath, "filePath", os.Getenv("PIPER_filePath"), "The path to the file to which the image should be saved.")
   127  	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/).")
   128  	cmd.Flags().StringVar(&stepConfig.ImageFormat, "imageFormat", `legacy`, "Format of the image when saving the docker image locally.")
   129  
   130  	cmd.MarkFlagRequired("containerRegistryUrl")
   131  	cmd.MarkFlagRequired("containerImage")
   132  }
   133  
   134  // retrieve step metadata
   135  func containerSaveImageMetadata() config.StepData {
   136  	var theMetaData = config.StepData{
   137  		Metadata: config.StepMetadata{
   138  			Name:        "containerSaveImage",
   139  			Aliases:     []config.Alias{},
   140  			Description: "Saves a container image as a tar file",
   141  		},
   142  		Spec: config.StepSpec{
   143  			Inputs: config.StepInputs{
   144  				Secrets: []config.StepSecrets{
   145  					{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}}},
   146  				},
   147  				Parameters: []config.StepParameters{
   148  					{
   149  						Name: "containerRegistryUrl",
   150  						ResourceRef: []config.ResourceReference{
   151  							{
   152  								Name:  "commonPipelineEnvironment",
   153  								Param: "container/registryUrl",
   154  							},
   155  						},
   156  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   157  						Type:      "string",
   158  						Mandatory: true,
   159  						Aliases:   []config.Alias{{Name: "dockerRegistryUrl"}},
   160  						Default:   os.Getenv("PIPER_containerRegistryUrl"),
   161  					},
   162  					{
   163  						Name: "containerImage",
   164  						ResourceRef: []config.ResourceReference{
   165  							{
   166  								Name:  "commonPipelineEnvironment",
   167  								Param: "container/imageNameTag",
   168  							},
   169  						},
   170  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   171  						Type:      "string",
   172  						Mandatory: true,
   173  						Aliases:   []config.Alias{{Name: "dockerImage"}, {Name: "scanImage"}},
   174  						Default:   os.Getenv("PIPER_containerImage"),
   175  					},
   176  					{
   177  						Name: "containerRegistryPassword",
   178  						ResourceRef: []config.ResourceReference{
   179  							{
   180  								Name:  "commonPipelineEnvironment",
   181  								Param: "container/repositoryPassword",
   182  							},
   183  
   184  							{
   185  								Name:  "commonPipelineEnvironment",
   186  								Param: "custom/repositoryPassword",
   187  							},
   188  						},
   189  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   190  						Type:      "string",
   191  						Mandatory: false,
   192  						Aliases:   []config.Alias{},
   193  						Default:   os.Getenv("PIPER_containerRegistryPassword"),
   194  					},
   195  					{
   196  						Name: "containerRegistryUser",
   197  						ResourceRef: []config.ResourceReference{
   198  							{
   199  								Name:  "commonPipelineEnvironment",
   200  								Param: "container/repositoryUsername",
   201  							},
   202  
   203  							{
   204  								Name:  "commonPipelineEnvironment",
   205  								Param: "custom/repositoryUsername",
   206  							},
   207  						},
   208  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   209  						Type:      "string",
   210  						Mandatory: false,
   211  						Aliases:   []config.Alias{},
   212  						Default:   os.Getenv("PIPER_containerRegistryUser"),
   213  					},
   214  					{
   215  						Name:        "filePath",
   216  						ResourceRef: []config.ResourceReference{},
   217  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   218  						Type:        "string",
   219  						Mandatory:   false,
   220  						Aliases:     []config.Alias{},
   221  						Default:     os.Getenv("PIPER_filePath"),
   222  					},
   223  					{
   224  						Name: "dockerConfigJSON",
   225  						ResourceRef: []config.ResourceReference{
   226  							{
   227  								Name:  "commonPipelineEnvironment",
   228  								Param: "custom/dockerConfigJSON",
   229  							},
   230  
   231  							{
   232  								Name: "dockerConfigJsonCredentialsId",
   233  								Type: "secret",
   234  							},
   235  
   236  							{
   237  								Name:    "dockerConfigFileVaultSecretName",
   238  								Type:    "vaultSecretFile",
   239  								Default: "docker-config",
   240  							},
   241  						},
   242  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   243  						Type:      "string",
   244  						Mandatory: false,
   245  						Aliases:   []config.Alias{},
   246  						Default:   os.Getenv("PIPER_dockerConfigJSON"),
   247  					},
   248  					{
   249  						Name:        "imageFormat",
   250  						ResourceRef: []config.ResourceReference{},
   251  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   252  						Type:        "string",
   253  						Mandatory:   false,
   254  						Aliases:     []config.Alias{},
   255  						Default:     `legacy`,
   256  					},
   257  				},
   258  			},
   259  		},
   260  	}
   261  	return theMetaData
   262  }