imagebuild

package
v0.0.0-...-47a5711 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2024 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Name  = string(cmd.ImageBuild)
	Usage = "Build container image using selected build engine"
	Alias = "bi"
)
View Source
const (
	FlagRuntimeLoad      = "runtime-load"
	FlagRuntimeLoadUsage = "container runtime where to load to created image"

	FlagEngine      = "engine"
	FlagEngineUsage = "container image build engine to use"

	FlagEngineEndpoint      = "engine-endpoint"
	FlagEngineEndpointUsage = "build engine endpoint address"

	FlagEngineToken      = "engine-token"
	FlagEngineTokenUsage = "build engine specific API token"

	FlagEngineNamespace      = "engine-namespace"
	FlagEngineNamespaceUsage = "build engine specific namespace"

	FlagImageName      = "image-name"
	FlagImageNameUsage = "container image name to use (including tag)"

	FlagImageArchiveFile      = "image-archive-file"
	FlagImageArchiveFileUsage = "local file path for the image tar archive file"

	FlagDockerfile      = "dockerfile"
	FlagDockerfileUsage = "local Dockerfile path (for buildkit and depot) or a relative to the build context directory (for docker or podman)"

	FlagContextDir      = "context-dir"
	FlagContextDirUsage = "local build context directory"

	FlagBuildArg      = "build-arg"
	FlagBuildArgUsage = "build time variable (ARG)"

	FlagLabel      = "label"
	FlagLabelUsage = "image label to add"

	FlagArchitecture      = "architecture"
	FlagArchitectureUsage = "build architecture"

	FlagBase      = "base"
	FlagBaseUsage = "base image to use (from selected runtime, docker by default, or pulled if not available)"

	FlagBaseTar      = "base-tar"
	FlagBaseTarUsage = "base image from a local tar file"

	FlagBaseWithCerts      = "base-with-certs"
	FlagBaseWithCertsUsage = "static-debian12 distroless base image - contains only certs and timezone info"

	FlagExePath      = "exe-path"
	FlagExePathUsage = "" /* 164-byte string literal not displayed */
)

ImageBuild command flag names and usage descriptions

View Source
const (
	DefaultImageName        = "mint-new-container-image:latest"
	DefaultImageArchiveFile = "mint-new-container-image.tar"
	DefaultDockerfilePath   = "Dockerfile"
	DefaultContextDir       = "."

	NoneRuntimeLoad   = "none"
	DockerRuntimeLoad = "docker"
	PodmanRuntimeLoad = "podman"

	DockerBuildEngine       = "docker"
	DockerBuildEngineInfo   = "Native Docker container build engine"
	BuildkitBuildEngine     = "buildkit"
	BuildkitBuildEngineInfo = "BuildKit container build engine"
	DepotBuildEngine        = "depot"
	DepotBuildEngineInfo    = "Depot.dev cloud-based container build engine"
	PodmanBuildEngine       = "podman"
	PodmanBuildEngineInfo   = "Native Podman/Buildah container build engine"
	SimpleBuildEngine       = "simple"
	SimpleBuildEngineInfo   = "Built-in container build engine for simple images that do not use 'RUN' instructions"

	Amd64Arch = "amd64"
	Arm64Arch = "arm64"

	DefaultRuntimeLoad = NoneRuntimeLoad
	DefaultEngineName  = DockerBuildEngine
)

Variables

View Source
var Architectures = map[string]struct{}{
	Amd64Arch: {},
	Arm64Arch: {},
}
View Source
var BuildEngines = map[string]BuildEngineProps{
	DockerBuildEngine: {Info: DockerBuildEngineInfo},
	BuildkitBuildEngine: {
		Info:             BuildkitBuildEngineInfo,
		EndpointRequired: true,
	},
	DepotBuildEngine: {
		Info:                  DepotBuildEngineInfo,
		TokenRequired:         true,
		NamespaceRequired:     true,
		NativeTokenEnvVar:     "DEPOT_TOKEN",
		NativeNamespaceEnvVar: "DEPOT_PROJECT_ID",
		NativeNamespaceName:   "project",
	},
	PodmanBuildEngine: {Info: PodmanBuildEngineInfo},
	SimpleBuildEngine: {Info: SimpleBuildEngineInfo},
}
View Source
var CLI = &cli.Command{
	Name:    Name,
	Aliases: []string{Alias},
	Usage:   Usage,
	Flags:   ImageBuildFlags,
	Action: func(ctx *cli.Context) error {
		logger := log.WithFields(log.Fields{"app": command.AppName, "cmd": Name, "op": "cli.Action"})

		gcvalues, ok := command.CLIContextGet(ctx.Context, command.GlobalParams).(*command.GenericParams)
		if !ok || gcvalues == nil {
			logger.Error("no gcvalues")
			return command.ErrNoGlobalParams
		}

		xc := app.NewExecutionContext(
			Name,
			gcvalues.QuietCLIMode,
			gcvalues.OutputFormat)

		cparams := &CommandParams{
			Engine:             ctx.String(FlagEngine),
			EngineEndpoint:     ctx.String(FlagEngineEndpoint),
			EngineToken:        ctx.String(FlagEngineToken),
			EngineNamespace:    ctx.String(FlagEngineNamespace),
			ImageName:          ctx.String(FlagImageName),
			ImageArchiveFile:   ctx.String(FlagImageArchiveFile),
			Dockerfile:         ctx.String(FlagDockerfile),
			ContextDir:         ctx.String(FlagContextDir),
			Architecture:       ctx.String(FlagArchitecture),
			BaseImage:          ctx.String(FlagBase),
			BaseImageTar:       ctx.String(FlagBaseTar),
			BaseImageWithCerts: ctx.Bool(FlagBaseWithCerts),
			ExePath:            ctx.String(FlagExePath),
			Labels:             map[string]string{},
		}

		loadRuntimeSet := map[string]struct{}{}
		for _, v := range ctx.StringSlice(FlagRuntimeLoad) {
			if IsRuntimeValue(v) {
				loadRuntimeSet[v] = struct{}{}
			}
		}

		for k := range loadRuntimeSet {
			cparams.LoadRuntimes = append(cparams.LoadRuntimes, k)
		}

		cboBuildArgs := command.ParseKVParams(ctx.StringSlice(FlagBuildArg))
		for _, val := range cboBuildArgs {
			cparams.BuildArgs = append(cparams.BuildArgs,
				imagebuilder.NVParam{Name: val.Name, Value: val.Value})
		}

		kvLabels := command.ParseKVParams(ctx.StringSlice(FlagLabel))
		for _, kv := range kvLabels {
			cparams.Labels[kv.Name] = kv.Value
		}

		engineProps, found := BuildEngines[cparams.Engine]
		if !found {
			logger.Errorf("engine not found - %s", cparams.Engine)
			return command.ErrBadParamValue
		}

		if cparams.Dockerfile == "" {
			cparams.Dockerfile = DefaultDockerfilePath
		}

		if !fsutil.DirExists(cparams.ContextDir) {
			logger.Errorf("context dir not found - %s", cparams.ContextDir)
			return command.ErrBadParamValue
		}

		switch cparams.Engine {
		case BuildkitBuildEngine, DepotBuildEngine:
			if !fsutil.Exists(cparams.Dockerfile) {
				logger.Errorf("Dockerfile not found - '%s'", cparams.Dockerfile)
				return command.ErrBadParamValue
			}
		case SimpleBuildEngine:
			if cparams.ExePath == "" && !fsutil.Exists(cparams.Dockerfile) {
				logger.Errorf("no exe-path and no Dockerfile - '%s'", cparams.Dockerfile)
				return command.ErrBadParamValue
			}
		default:
			fullDockerfilePath := filepath.Join(cparams.ContextDir, cparams.Dockerfile)
			if !fsutil.Exists(fullDockerfilePath) {
				logger.Errorf("Dockerfile not found - '%s' ('%s')", cparams.Dockerfile, fullDockerfilePath)
				return command.ErrBadParamValue
			}
		}

		if cparams.Architecture == "" {
			cparams.Architecture = GetDefaultBuildArch()
		}

		if !IsArchValue(cparams.Architecture) {
			logger.Errorf("architecture not supported - %s", cparams.Architecture)
			return command.ErrBadParamValue
		}

		if engineProps.TokenRequired &&
			cparams.EngineToken == "" &&
			engineProps.NativeTokenEnvVar != "" {
			cparams.EngineToken = os.Getenv(engineProps.NativeTokenEnvVar)
		}

		if engineProps.NamespaceRequired &&
			cparams.EngineNamespace == "" &&
			engineProps.NativeNamespaceEnvVar != "" {
			cparams.EngineNamespace = os.Getenv(engineProps.NativeNamespaceEnvVar)
		}

		if engineProps.TokenRequired && cparams.EngineToken == "" {
			return fmt.Errorf("missing flag value - %s", FlagEngineToken)
		}

		if engineProps.NamespaceRequired && cparams.EngineNamespace == "" {
			return fmt.Errorf("missing flag value - %s", FlagEngineNamespace)
		}

		if engineProps.EndpointRequired && cparams.EngineEndpoint == "" {
			return fmt.Errorf("missing flag value - %s", FlagEngineEndpoint)
		}

		if cparams.ImageName == "" {
			return fmt.Errorf("missing flag value - %s", FlagImageName)
		}

		if cparams.ImageArchiveFile == "" {
			return fmt.Errorf("missing flag value - %s", FlagImageArchiveFile)
		}

		if !strings.Contains(cparams.ImageName, ":") {
			cparams.ImageName = fmt.Sprintf("%s:latest", cparams.ImageName)
		}

		OnCommand(xc, gcvalues, cparams)
		return nil
	},
}
View Source
var CommandFlagSuggestions = &command.FlagSuggestions{
	Names: []prompt.Suggest{
		{Text: command.FullFlagName(FlagEngine), Description: FlagEngineUsage},
		{Text: command.FullFlagName(FlagRuntimeLoad), Description: FlagRuntimeLoadUsage},
		{Text: command.FullFlagName(FlagEngineEndpoint), Description: FlagEngineEndpointUsage},
		{Text: command.FullFlagName(FlagEngineToken), Description: FlagEngineTokenUsage},
		{Text: command.FullFlagName(FlagEngineNamespace), Description: FlagEngineNamespaceUsage},
		{Text: command.FullFlagName(FlagImageName), Description: FlagImageNameUsage},
		{Text: command.FullFlagName(FlagImageArchiveFile), Description: FlagImageArchiveFileUsage},
		{Text: command.FullFlagName(FlagDockerfile), Description: FlagDockerfileUsage},
		{Text: command.FullFlagName(FlagContextDir), Description: FlagContextDirUsage},
		{Text: command.FullFlagName(FlagBuildArg), Description: FlagBuildArgUsage},
		{Text: command.FullFlagName(FlagLabel), Description: FlagLabelUsage},
		{Text: command.FullFlagName(FlagArchitecture), Description: FlagArchitectureUsage},
		{Text: command.FullFlagName(FlagBase), Description: FlagBaseUsage},
		{Text: command.FullFlagName(FlagBaseTar), Description: FlagBaseTarUsage},
		{Text: command.FullFlagName(FlagBaseWithCerts), Description: FlagBaseWithCertsUsage},
		{Text: command.FullFlagName(FlagExePath), Description: FlagExePathUsage},
	},
	Values: map[string]command.CompleteValue{
		command.FullFlagName(FlagEngine):        completeBuildEngine,
		command.FullFlagName(FlagRuntimeLoad):   completeRuntimeLoad,
		command.FullFlagName(FlagArchitecture):  completeArchitecture,
		command.FullFlagName(FlagContextDir):    command.CompleteDir,
		command.FullFlagName(FlagBaseTar):       command.CompleteFile,
		command.FullFlagName(FlagBaseWithCerts): command.CompleteBool,
		command.FullFlagName(FlagExePath):       command.CompleteFile,
	},
}
View Source
var CommandSuggestion = prompt.Suggest{
	Text:        Name,
	Description: Usage,
}
View Source
var Flags = map[string]cli.Flag{
	FlagEngine: &cli.StringFlag{
		Name:    FlagEngine,
		Value:   DefaultEngineName,
		Usage:   FlagEngineUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_ENGINE"},
	},
	FlagEngineEndpoint: &cli.StringFlag{
		Name:    FlagEngineEndpoint,
		Value:   "",
		Usage:   FlagEngineEndpointUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_ENGINE_ENDPOINT"},
	},
	FlagEngineToken: &cli.StringFlag{
		Name:    FlagEngineToken,
		Value:   "",
		Usage:   FlagEngineTokenUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_ENGINE_TOKEN"},
	},
	FlagEngineNamespace: &cli.StringFlag{
		Name:    FlagEngineNamespace,
		Value:   "",
		Usage:   FlagEngineNamespaceUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_ENGINE_NS"},
	},
	FlagImageName: &cli.StringFlag{
		Name:    FlagImageName,
		Value:   DefaultImageName,
		Usage:   FlagImageNameUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_IMAGE_NAME"},
	},
	FlagImageArchiveFile: &cli.StringFlag{
		Name:    FlagImageArchiveFile,
		Value:   DefaultImageArchiveFile,
		Usage:   FlagImageArchiveFileUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_IMAGE_ARCHIVE"},
	},
	FlagDockerfile: &cli.StringFlag{
		Name:    FlagDockerfile,
		Value:   DefaultDockerfilePath,
		Usage:   FlagDockerfileUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_DOCKERFILE"},
	},
	FlagContextDir: &cli.StringFlag{
		Name:    FlagContextDir,
		Value:   DefaultContextDir,
		Usage:   FlagContextDirUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_CONTEXT_DIR"},
	},
	FlagBuildArg: &cli.StringSliceFlag{
		Name:    FlagBuildArg,
		Value:   cli.NewStringSlice(""),
		Usage:   FlagBuildArgUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_BUILD_ARGS"},
	},
	FlagLabel: &cli.StringSliceFlag{
		Name:    FlagLabel,
		Value:   cli.NewStringSlice(""),
		Usage:   FlagLabelUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_LABELS"},
	},
	FlagRuntimeLoad: &cli.StringSliceFlag{
		Name:    FlagRuntimeLoad,
		Usage:   FlagRuntimeLoadUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_RUNTIME_LOAD"},
	},
	FlagArchitecture: &cli.StringFlag{
		Name:    FlagArchitecture,
		Value:   GetDefaultBuildArch(),
		Usage:   FlagArchitectureUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_ARCH"},
	},
	FlagBase: &cli.StringFlag{
		Name:    FlagBase,
		Value:   "",
		Usage:   FlagBaseUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_BASE"},
	},
	FlagBaseTar: &cli.StringFlag{
		Name:    FlagBaseTar,
		Value:   "",
		Usage:   FlagBaseTarUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_BASE_TAR"},
	},
	FlagBaseWithCerts: &cli.BoolFlag{
		Name:    FlagBaseWithCerts,
		Usage:   FlagBaseWithCertsUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_BASE_WITH_CERTS"},
	},
	FlagExePath: &cli.StringFlag{
		Name:    FlagExePath,
		Value:   "",
		Usage:   FlagExePathUsage,
		EnvVars: []string{"DSLIM_IMAGEBUILD_EXE_PATH"},
	},
}
View Source
var ImageBuildFlags = useAllFlags()
View Source
var Runtimes = map[string]struct{}{
	NoneRuntimeLoad:   {},
	DockerRuntimeLoad: {},
	PodmanRuntimeLoad: {},
}

Functions

func GetDefaultBuildArch

func GetDefaultBuildArch() string

func HandleBuildkitEngine

func HandleBuildkitEngine(
	logger *log.Entry,
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams)

HandleBuildkitEngine implements support for the Buildkit container build engine

func HandleDepotEngine

func HandleDepotEngine(
	logger *log.Entry,
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams)

HandleDepotEngine implements support for the Depot.dev container build engine

func HandleDockerEngine

func HandleDockerEngine(
	logger *log.Entry,
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams,
	client *dockerapi.Client)

HandleDockerEngine implements support for the Docker container build engine

func HandlePodmanEngine

func HandlePodmanEngine(
	logger *log.Entry,
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams,
	client context.Context)

HandlePodmanEngine implements support for the Podman container build engine

func HandleSimpleEngine

func HandleSimpleEngine(
	logger *log.Entry,
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams,
	client *dockerapi.Client)

HandleSimpleEngine implements support for the simple built-in container build engine

func IsArchValue

func IsArchValue(name string) bool

func IsRuntimeValue

func IsRuntimeValue(name string) bool

func OnCommand

func OnCommand(
	xc *app.ExecutionContext,
	gparams *command.GenericParams,
	cparams *CommandParams)

OnCommand implements the 'imagebuild' command

func RegisterCommand

func RegisterCommand()

Types

type BuildEngineProps

type BuildEngineProps struct {
	Info                  string
	TokenRequired         bool
	NamespaceRequired     bool
	EndpointRequired      bool
	NativeTokenEnvVar     string
	NativeNamespaceEnvVar string
	NativeNamespaceName   string
	DefaultEndpoint       string
}

type CommandParams

type CommandParams struct {
	Engine             string                 `json:"engine,omitempty"`
	EngineEndpoint     string                 `json:"engine_endpoint,omitempty"`
	EngineToken        string                 `json:"engine_token,omitempty"`
	EngineNamespace    string                 `json:"engine_namespace,omitempty"`
	ImageName          string                 `json:"image_name,omitempty"`
	ImageArchiveFile   string                 `json:"image_archive_file,omitempty"`
	LoadRuntimes       []string               `json:"runtime,omitempty"` //runtime where to load the created image
	Dockerfile         string                 `json:"dockerfile,omitempty"`
	ContextDir         string                 `json:"context_dir,omitempty"`
	BuildArgs          []imagebuilder.NVParam `json:"build_args,omitempty"`
	Labels             map[string]string      `json:"labels,omitempty"`
	Architecture       string                 `json:"architecture,omitempty"`
	BaseImage          string                 `json:"base_image,omitempty"`
	BaseImageTar       string                 `json:"base_image_tar,omitempty"`
	BaseImageWithCerts bool                   `json:"base_image_with_certs,omitempty"`
	ExePath            string                 `json:"exe_path,omitempty"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL