github.com/Hashicorp/packer@v1.3.2/builder/lxd/builder.go (about)

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