github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/engine/builder/dockerfile/builder.go (about)

     1  package dockerfile // import "github.com/docker/docker/builder/dockerfile"
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"io"
     8  	"sort"
     9  	"strings"
    10  
    11  	"github.com/containerd/containerd/platforms"
    12  	"github.com/docker/docker/api/types"
    13  	"github.com/docker/docker/api/types/backend"
    14  	"github.com/docker/docker/api/types/container"
    15  	"github.com/docker/docker/builder"
    16  	"github.com/docker/docker/builder/remotecontext"
    17  	"github.com/docker/docker/errdefs"
    18  	"github.com/docker/docker/pkg/idtools"
    19  	"github.com/docker/docker/pkg/streamformatter"
    20  	"github.com/docker/docker/pkg/stringid"
    21  	"github.com/docker/docker/pkg/system"
    22  	"github.com/moby/buildkit/frontend/dockerfile/instructions"
    23  	"github.com/moby/buildkit/frontend/dockerfile/parser"
    24  	"github.com/moby/buildkit/frontend/dockerfile/shell"
    25  	specs "github.com/opencontainers/image-spec/specs-go/v1"
    26  	"github.com/pkg/errors"
    27  	"github.com/sirupsen/logrus"
    28  	"golang.org/x/sync/syncmap"
    29  )
    30  
    31  var validCommitCommands = map[string]bool{
    32  	"cmd":         true,
    33  	"entrypoint":  true,
    34  	"healthcheck": true,
    35  	"env":         true,
    36  	"expose":      true,
    37  	"label":       true,
    38  	"onbuild":     true,
    39  	"user":        true,
    40  	"volume":      true,
    41  	"workdir":     true,
    42  }
    43  
    44  const (
    45  	stepFormat = "Step %d/%d : %v"
    46  )
    47  
    48  // BuildManager is shared across all Builder objects
    49  type BuildManager struct {
    50  	idMapping *idtools.IdentityMapping
    51  	backend   builder.Backend
    52  	pathCache pathCache // TODO: make this persistent
    53  }
    54  
    55  // NewBuildManager creates a BuildManager
    56  func NewBuildManager(b builder.Backend, identityMapping *idtools.IdentityMapping) (*BuildManager, error) {
    57  	bm := &BuildManager{
    58  		backend:   b,
    59  		pathCache: &syncmap.Map{},
    60  		idMapping: identityMapping,
    61  	}
    62  	return bm, nil
    63  }
    64  
    65  // Build starts a new build from a BuildConfig
    66  func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
    67  	buildsTriggered.Inc()
    68  	if config.Options.Dockerfile == "" {
    69  		config.Options.Dockerfile = builder.DefaultDockerfileName
    70  	}
    71  
    72  	source, dockerfile, err := remotecontext.Detect(config)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	defer func() {
    77  		if source != nil {
    78  			if err := source.Close(); err != nil {
    79  				logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
    80  			}
    81  		}
    82  	}()
    83  
    84  	ctx, cancel := context.WithCancel(ctx)
    85  	defer cancel()
    86  
    87  	builderOptions := builderOptions{
    88  		Options:        config.Options,
    89  		ProgressWriter: config.ProgressWriter,
    90  		Backend:        bm.backend,
    91  		PathCache:      bm.pathCache,
    92  		IDMapping:      bm.idMapping,
    93  	}
    94  	b, err := newBuilder(ctx, builderOptions)
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  	return b.build(source, dockerfile)
    99  }
   100  
   101  // builderOptions are the dependencies required by the builder
   102  type builderOptions struct {
   103  	Options        *types.ImageBuildOptions
   104  	Backend        builder.Backend
   105  	ProgressWriter backend.ProgressWriter
   106  	PathCache      pathCache
   107  	IDMapping      *idtools.IdentityMapping
   108  }
   109  
   110  // Builder is a Dockerfile builder
   111  // It implements the builder.Backend interface.
   112  type Builder struct {
   113  	options *types.ImageBuildOptions
   114  
   115  	Stdout io.Writer
   116  	Stderr io.Writer
   117  	Aux    *streamformatter.AuxFormatter
   118  	Output io.Writer
   119  
   120  	docker    builder.Backend
   121  	clientCtx context.Context
   122  
   123  	idMapping        *idtools.IdentityMapping
   124  	disableCommit    bool
   125  	imageSources     *imageSources
   126  	pathCache        pathCache
   127  	containerManager *containerManager
   128  	imageProber      ImageProber
   129  	platform         *specs.Platform
   130  }
   131  
   132  // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
   133  func newBuilder(clientCtx context.Context, options builderOptions) (*Builder, error) {
   134  	config := options.Options
   135  	if config == nil {
   136  		config = new(types.ImageBuildOptions)
   137  	}
   138  
   139  	b := &Builder{
   140  		clientCtx:        clientCtx,
   141  		options:          config,
   142  		Stdout:           options.ProgressWriter.StdoutFormatter,
   143  		Stderr:           options.ProgressWriter.StderrFormatter,
   144  		Aux:              options.ProgressWriter.AuxFormatter,
   145  		Output:           options.ProgressWriter.Output,
   146  		docker:           options.Backend,
   147  		idMapping:        options.IDMapping,
   148  		imageSources:     newImageSources(clientCtx, options),
   149  		pathCache:        options.PathCache,
   150  		imageProber:      newImageProber(options.Backend, config.CacheFrom, config.NoCache),
   151  		containerManager: newContainerManager(options.Backend),
   152  	}
   153  
   154  	// same as in Builder.Build in builder/builder-next/builder.go
   155  	// TODO: remove once config.Platform is of type specs.Platform
   156  	if config.Platform != "" {
   157  		sp, err := platforms.Parse(config.Platform)
   158  		if err != nil {
   159  			return nil, err
   160  		}
   161  		if err := system.ValidatePlatform(sp); err != nil {
   162  			return nil, err
   163  		}
   164  		b.platform = &sp
   165  	}
   166  
   167  	return b, nil
   168  }
   169  
   170  // Build 'LABEL' command(s) from '--label' options and add to the last stage
   171  func buildLabelOptions(labels map[string]string, stages []instructions.Stage) {
   172  	keys := []string{}
   173  	for key := range labels {
   174  		keys = append(keys, key)
   175  	}
   176  
   177  	// Sort the label to have a repeatable order
   178  	sort.Strings(keys)
   179  	for _, key := range keys {
   180  		value := labels[key]
   181  		stages[len(stages)-1].AddCommand(instructions.NewLabelCommand(key, value, true))
   182  	}
   183  }
   184  
   185  // Build runs the Dockerfile builder by parsing the Dockerfile and executing
   186  // the instructions from the file.
   187  func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
   188  	defer b.imageSources.Unmount()
   189  
   190  	stages, metaArgs, err := instructions.Parse(dockerfile.AST)
   191  	if err != nil {
   192  		var uiErr *instructions.UnknownInstruction
   193  		if errors.As(err, &uiErr) {
   194  			buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
   195  		}
   196  		return nil, errdefs.InvalidParameter(err)
   197  	}
   198  	if b.options.Target != "" {
   199  		targetIx, found := instructions.HasStage(stages, b.options.Target)
   200  		if !found {
   201  			buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
   202  			return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
   203  		}
   204  		stages = stages[:targetIx+1]
   205  	}
   206  
   207  	// Add 'LABEL' command specified by '--label' option to the last stage
   208  	buildLabelOptions(b.options.Labels, stages)
   209  
   210  	dockerfile.PrintWarnings(b.Stderr)
   211  	dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
   212  	if err != nil {
   213  		return nil, err
   214  	}
   215  	if dispatchState.imageID == "" {
   216  		buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
   217  		return nil, errors.New("No image was generated. Is your Dockerfile empty?")
   218  	}
   219  	return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
   220  }
   221  
   222  func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
   223  	if aux == nil || state.imageID == "" {
   224  		return nil
   225  	}
   226  	return aux.Emit("", types.BuildResult{ID: state.imageID})
   227  }
   228  
   229  func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *BuildArgs) error {
   230  	// shell.Lex currently only support the concatenated string format
   231  	envs := convertMapToEnvList(args.GetAllAllowed())
   232  	if err := meta.Expand(func(word string) (string, error) {
   233  		return shlex.ProcessWord(word, envs)
   234  	}); err != nil {
   235  		return err
   236  	}
   237  	for _, arg := range meta.Args {
   238  		args.AddArg(arg.Key, arg.Value)
   239  		args.AddMetaArg(arg.Key, arg.Value)
   240  	}
   241  	return nil
   242  }
   243  
   244  func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd interface{}) int {
   245  	fmt.Fprintf(out, stepFormat, currentCommandIndex, totalCommands, cmd)
   246  	fmt.Fprintln(out)
   247  	return currentCommandIndex + 1
   248  }
   249  
   250  func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
   251  	dispatchRequest := dispatchRequest{}
   252  	buildArgs := NewBuildArgs(b.options.BuildArgs)
   253  	totalCommands := len(metaArgs) + len(parseResult)
   254  	currentCommandIndex := 1
   255  	for _, stage := range parseResult {
   256  		totalCommands += len(stage.Commands)
   257  	}
   258  	shlex := shell.NewLex(escapeToken)
   259  	for i := range metaArgs {
   260  		currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &metaArgs[i])
   261  
   262  		err := processMetaArg(metaArgs[i], shlex, buildArgs)
   263  		if err != nil {
   264  			return nil, err
   265  		}
   266  	}
   267  
   268  	stagesResults := newStagesBuildResults()
   269  
   270  	for _, s := range parseResult {
   271  		stage := s
   272  		if err := stagesResults.checkStageNameAvailable(stage.Name); err != nil {
   273  			return nil, err
   274  		}
   275  		dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
   276  
   277  		currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
   278  		if err := initializeStage(dispatchRequest, &stage); err != nil {
   279  			return nil, err
   280  		}
   281  		dispatchRequest.state.updateRunConfig()
   282  		fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
   283  		for _, cmd := range stage.Commands {
   284  			select {
   285  			case <-b.clientCtx.Done():
   286  				logrus.Debug("Builder: build cancelled!")
   287  				fmt.Fprint(b.Stdout, "Build cancelled\n")
   288  				buildsFailed.WithValues(metricsBuildCanceled).Inc()
   289  				return nil, errors.New("Build cancelled")
   290  			default:
   291  				// Not cancelled yet, keep going...
   292  			}
   293  
   294  			currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
   295  
   296  			if err := dispatch(dispatchRequest, cmd); err != nil {
   297  				return nil, err
   298  			}
   299  			dispatchRequest.state.updateRunConfig()
   300  			fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
   301  
   302  		}
   303  		if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
   304  			return nil, err
   305  		}
   306  		buildArgs.MergeReferencedArgs(dispatchRequest.state.buildArgs)
   307  		if err := commitStage(dispatchRequest.state, stagesResults); err != nil {
   308  			return nil, err
   309  		}
   310  	}
   311  	buildArgs.WarnOnUnusedBuildArgs(b.Stdout)
   312  	return dispatchRequest.state, nil
   313  }
   314  
   315  // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
   316  // It will:
   317  // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
   318  // - Do build by calling builder.dispatch() to call all entries' handling routines
   319  //
   320  // BuildFromConfig is used by the /commit endpoint, with the changes
   321  // coming from the query parameter of the same name.
   322  //
   323  // TODO: Remove?
   324  func BuildFromConfig(config *container.Config, changes []string, os string) (*container.Config, error) {
   325  	if !system.IsOSSupported(os) {
   326  		return nil, errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
   327  	}
   328  	if len(changes) == 0 {
   329  		return config, nil
   330  	}
   331  
   332  	dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
   333  	if err != nil {
   334  		return nil, errdefs.InvalidParameter(err)
   335  	}
   336  
   337  	b, err := newBuilder(context.Background(), builderOptions{
   338  		Options: &types.ImageBuildOptions{NoCache: true},
   339  	})
   340  	if err != nil {
   341  		return nil, err
   342  	}
   343  
   344  	// ensure that the commands are valid
   345  	for _, n := range dockerfile.AST.Children {
   346  		if !validCommitCommands[n.Value] {
   347  			return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value))
   348  		}
   349  	}
   350  
   351  	b.Stdout = io.Discard
   352  	b.Stderr = io.Discard
   353  	b.disableCommit = true
   354  
   355  	var commands []instructions.Command
   356  	for _, n := range dockerfile.AST.Children {
   357  		cmd, err := instructions.ParseCommand(n)
   358  		if err != nil {
   359  			return nil, errdefs.InvalidParameter(err)
   360  		}
   361  		commands = append(commands, cmd)
   362  	}
   363  
   364  	dispatchRequest := newDispatchRequest(b, dockerfile.EscapeToken, nil, NewBuildArgs(b.options.BuildArgs), newStagesBuildResults())
   365  	// We make mutations to the configuration, ensure we have a copy
   366  	dispatchRequest.state.runConfig = copyRunConfig(config)
   367  	dispatchRequest.state.imageID = config.Image
   368  	dispatchRequest.state.operatingSystem = os
   369  	for _, cmd := range commands {
   370  		err := dispatch(dispatchRequest, cmd)
   371  		if err != nil {
   372  			return nil, errdefs.InvalidParameter(err)
   373  		}
   374  		dispatchRequest.state.updateRunConfig()
   375  	}
   376  
   377  	return dispatchRequest.state.runConfig, nil
   378  }
   379  
   380  func convertMapToEnvList(m map[string]string) []string {
   381  	result := []string{}
   382  	for k, v := range m {
   383  		result = append(result, k+"="+v)
   384  	}
   385  	return result
   386  }