github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/builder/docker/builder.go (about)

     1  package docker
     2  
     3  import (
     4  	"github.com/mitchellh/multistep"
     5  	"github.com/mitchellh/packer/common"
     6  	"github.com/mitchellh/packer/packer"
     7  	"log"
     8  )
     9  
    10  const BuilderId = "packer.docker"
    11  const BuilderIdImport = "packer.post-processor.docker-import"
    12  
    13  type Builder struct {
    14  	config *Config
    15  	runner multistep.Runner
    16  }
    17  
    18  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    19  	c, warnings, errs := NewConfig(raws...)
    20  	if errs != nil {
    21  		return warnings, errs
    22  	}
    23  	b.config = c
    24  
    25  	return warnings, nil
    26  }
    27  
    28  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
    29  	driver := &DockerDriver{Tpl: b.config.tpl, Ui: ui}
    30  	if err := driver.Verify(); err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	steps := []multistep.Step{
    35  		&StepTempDir{},
    36  		&StepPull{},
    37  		&StepRun{},
    38  		&StepProvision{},
    39  	}
    40  
    41  	if b.config.Commit {
    42  		steps = append(steps, new(StepCommit))
    43  	} else {
    44  		steps = append(steps, new(StepExport))
    45  	}
    46  
    47  	// Setup the state bag and initial state for the steps
    48  	state := new(multistep.BasicStateBag)
    49  	state.Put("config", b.config)
    50  	state.Put("hook", hook)
    51  	state.Put("ui", ui)
    52  
    53  	// Setup the driver that will talk to Docker
    54  	state.Put("driver", driver)
    55  
    56  	// Run!
    57  	if b.config.PackerDebug {
    58  		b.runner = &multistep.DebugRunner{
    59  			Steps:   steps,
    60  			PauseFn: common.MultistepDebugFn(ui),
    61  		}
    62  	} else {
    63  		b.runner = &multistep.BasicRunner{Steps: steps}
    64  	}
    65  
    66  	b.runner.Run(state)
    67  
    68  	// If there was an error, return that
    69  	if rawErr, ok := state.GetOk("error"); ok {
    70  		return nil, rawErr.(error)
    71  	}
    72  
    73  	var artifact packer.Artifact
    74  	// No errors, must've worked
    75  	if b.config.Commit {
    76  		artifact = &ImportArtifact{
    77  			IdValue:        state.Get("image_id").(string),
    78  			BuilderIdValue: BuilderIdImport,
    79  			Driver:         driver,
    80  		}
    81  	} else {
    82  		artifact = &ExportArtifact{path: b.config.ExportPath}
    83  	}
    84  	return artifact, nil
    85  }
    86  
    87  func (b *Builder) Cancel() {
    88  	if b.runner != nil {
    89  		log.Println("Cancelling the step runner...")
    90  		b.runner.Cancel()
    91  	}
    92  }