github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/lxd/builder.go (about)

     1  package lxd
     2  
     3  import (
     4  	"github.com/hashicorp/packer/common"
     5  	"github.com/hashicorp/packer/packer"
     6  	"github.com/hashicorp/packer/template/interpolate"
     7  	"github.com/mitchellh/multistep"
     8  	"log"
     9  )
    10  
    11  // The unique ID for this builder
    12  const BuilderId = "lxd"
    13  
    14  type wrappedCommandTemplate struct {
    15  	Command string
    16  }
    17  
    18  type Builder struct {
    19  	config *Config
    20  	runner multistep.Runner
    21  }
    22  
    23  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    24  	c, errs := NewConfig(raws...)
    25  	if errs != nil {
    26  		return nil, errs
    27  	}
    28  	b.config = c
    29  
    30  	return nil, nil
    31  }
    32  
    33  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
    34  	wrappedCommand := func(command string) (string, error) {
    35  		b.config.ctx.Data = &wrappedCommandTemplate{Command: command}
    36  		return interpolate.Render(b.config.CommandWrapper, &b.config.ctx)
    37  	}
    38  
    39  	steps := []multistep.Step{
    40  		&stepLxdLaunch{},
    41  		&StepProvision{},
    42  		&stepPublish{},
    43  	}
    44  
    45  	// Setup the state bag
    46  	state := new(multistep.BasicStateBag)
    47  	state.Put("config", b.config)
    48  	state.Put("cache", cache)
    49  	state.Put("hook", hook)
    50  	state.Put("ui", ui)
    51  	state.Put("wrappedCommand", CommandWrapper(wrappedCommand))
    52  
    53  	// Run
    54  	b.runner = common.NewRunnerWithPauseFn(steps, b.config.PackerConfig, ui, state)
    55  	b.runner.Run(state)
    56  
    57  	// If there was an error, return that
    58  	if rawErr, ok := state.GetOk("error"); ok {
    59  		return nil, rawErr.(error)
    60  	}
    61  
    62  	artifact := &Artifact{
    63  		id: state.Get("imageFingerprint").(string),
    64  	}
    65  
    66  	return artifact, nil
    67  }
    68  
    69  func (b *Builder) Cancel() {
    70  	if b.runner != nil {
    71  		log.Println("Cancelling the step runner...")
    72  		b.runner.Cancel()
    73  	}
    74  }