github.com/endocode/docker@v1.4.2-0.20160113120958-46eb4700391e/builder/dockerfile/builder.go (about)

     1  package dockerfile
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"strings"
    10  	"sync"
    11  
    12  	"github.com/Sirupsen/logrus"
    13  	"github.com/docker/docker/builder"
    14  	"github.com/docker/docker/builder/dockerfile/parser"
    15  	"github.com/docker/docker/pkg/stringid"
    16  	"github.com/docker/engine-api/types"
    17  	"github.com/docker/engine-api/types/container"
    18  )
    19  
    20  var validCommitCommands = map[string]bool{
    21  	"cmd":        true,
    22  	"entrypoint": true,
    23  	"env":        true,
    24  	"expose":     true,
    25  	"label":      true,
    26  	"onbuild":    true,
    27  	"user":       true,
    28  	"volume":     true,
    29  	"workdir":    true,
    30  }
    31  
    32  // BuiltinAllowedBuildArgs is list of built-in allowed build args
    33  var BuiltinAllowedBuildArgs = map[string]bool{
    34  	"HTTP_PROXY":  true,
    35  	"http_proxy":  true,
    36  	"HTTPS_PROXY": true,
    37  	"https_proxy": true,
    38  	"FTP_PROXY":   true,
    39  	"ftp_proxy":   true,
    40  	"NO_PROXY":    true,
    41  	"no_proxy":    true,
    42  }
    43  
    44  // Builder is a Dockerfile builder
    45  // It implements the builder.Backend interface.
    46  type Builder struct {
    47  	options *types.ImageBuildOptions
    48  
    49  	Stdout io.Writer
    50  	Stderr io.Writer
    51  
    52  	docker  builder.Backend
    53  	context builder.Context
    54  
    55  	dockerfile       *parser.Node
    56  	runConfig        *container.Config // runconfig for cmd, run, entrypoint etc.
    57  	flags            *BFlags
    58  	tmpContainers    map[string]struct{}
    59  	image            string // imageID
    60  	noBaseImage      bool
    61  	maintainer       string
    62  	cmdSet           bool
    63  	disableCommit    bool
    64  	cacheBusted      bool
    65  	cancelled        chan struct{}
    66  	cancelOnce       sync.Once
    67  	allowedBuildArgs map[string]bool // list of build-time args that are allowed for expansion/substitution and passing to commands in 'run'.
    68  
    69  	// TODO: remove once docker.Commit can receive a tag
    70  	id string
    71  }
    72  
    73  // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
    74  // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
    75  // will be read from the Context passed to Build().
    76  func NewBuilder(config *types.ImageBuildOptions, backend builder.Backend, context builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
    77  	if config == nil {
    78  		config = new(types.ImageBuildOptions)
    79  	}
    80  	if config.BuildArgs == nil {
    81  		config.BuildArgs = make(map[string]string)
    82  	}
    83  	b = &Builder{
    84  		options:          config,
    85  		Stdout:           os.Stdout,
    86  		Stderr:           os.Stderr,
    87  		docker:           backend,
    88  		context:          context,
    89  		runConfig:        new(container.Config),
    90  		tmpContainers:    map[string]struct{}{},
    91  		cancelled:        make(chan struct{}),
    92  		id:               stringid.GenerateNonCryptoID(),
    93  		allowedBuildArgs: make(map[string]bool),
    94  	}
    95  	if dockerfile != nil {
    96  		b.dockerfile, err = parser.Parse(dockerfile)
    97  		if err != nil {
    98  			return nil, err
    99  		}
   100  	}
   101  
   102  	return b, nil
   103  }
   104  
   105  // Build runs the Dockerfile builder from a context and a docker object that allows to make calls
   106  // to Docker.
   107  //
   108  // This will (barring errors):
   109  //
   110  // * read the dockerfile from context
   111  // * parse the dockerfile if not already parsed
   112  // * walk the AST and execute it by dispatching to handlers. If Remove
   113  //   or ForceRemove is set, additional cleanup around containers happens after
   114  //   processing.
   115  // * Print a happy message and return the image ID.
   116  // * NOT tag the image, that is responsibility of the caller.
   117  //
   118  func (b *Builder) Build() (string, error) {
   119  	// If Dockerfile was not parsed yet, extract it from the Context
   120  	if b.dockerfile == nil {
   121  		if err := b.readDockerfile(); err != nil {
   122  			return "", err
   123  		}
   124  	}
   125  
   126  	var shortImgID string
   127  	for i, n := range b.dockerfile.Children {
   128  		select {
   129  		case <-b.cancelled:
   130  			logrus.Debug("Builder: build cancelled!")
   131  			fmt.Fprintf(b.Stdout, "Build cancelled")
   132  			return "", fmt.Errorf("Build cancelled")
   133  		default:
   134  			// Not cancelled yet, keep going...
   135  		}
   136  		if err := b.dispatch(i, n); err != nil {
   137  			if b.options.ForceRemove {
   138  				b.clearTmp()
   139  			}
   140  			return "", err
   141  		}
   142  		shortImgID = stringid.TruncateID(b.image)
   143  		fmt.Fprintf(b.Stdout, " ---> %s\n", shortImgID)
   144  		if b.options.Remove {
   145  			b.clearTmp()
   146  		}
   147  	}
   148  
   149  	// check if there are any leftover build-args that were passed but not
   150  	// consumed during build. Return an error, if there are any.
   151  	leftoverArgs := []string{}
   152  	for arg := range b.options.BuildArgs {
   153  		if !b.isBuildArgAllowed(arg) {
   154  			leftoverArgs = append(leftoverArgs, arg)
   155  		}
   156  	}
   157  	if len(leftoverArgs) > 0 {
   158  		return "", fmt.Errorf("One or more build-args %v were not consumed, failing build.", leftoverArgs)
   159  	}
   160  
   161  	if b.image == "" {
   162  		return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?")
   163  	}
   164  
   165  	fmt.Fprintf(b.Stdout, "Successfully built %s\n", shortImgID)
   166  	return b.image, nil
   167  }
   168  
   169  // Cancel cancels an ongoing Dockerfile build.
   170  func (b *Builder) Cancel() {
   171  	b.cancelOnce.Do(func() {
   172  		close(b.cancelled)
   173  	})
   174  }
   175  
   176  // BuildFromConfig will do build directly from parameter 'changes', which comes
   177  // from Dockerfile entries, it will:
   178  // - call parse.Parse() to get AST root from Dockerfile entries
   179  // - do build by calling builder.dispatch() to call all entries' handling routines
   180  // TODO: remove?
   181  func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
   182  	ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
   183  	if err != nil {
   184  		return nil, err
   185  	}
   186  
   187  	// ensure that the commands are valid
   188  	for _, n := range ast.Children {
   189  		if !validCommitCommands[n.Value] {
   190  			return nil, fmt.Errorf("%s is not a valid change command", n.Value)
   191  		}
   192  	}
   193  
   194  	b, err := NewBuilder(nil, nil, nil, nil)
   195  	if err != nil {
   196  		return nil, err
   197  	}
   198  	b.runConfig = config
   199  	b.Stdout = ioutil.Discard
   200  	b.Stderr = ioutil.Discard
   201  	b.disableCommit = true
   202  
   203  	for i, n := range ast.Children {
   204  		if err := b.dispatch(i, n); err != nil {
   205  			return nil, err
   206  		}
   207  	}
   208  
   209  	return b.runConfig, nil
   210  }