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

     1  package docker
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/hashicorp/packer/packer"
     9  	"github.com/mitchellh/multistep"
    10  )
    11  
    12  // StepExport exports the container to a flat tar file.
    13  type StepExport struct{}
    14  
    15  func (s *StepExport) Run(state multistep.StateBag) multistep.StepAction {
    16  	config := state.Get("config").(*Config)
    17  
    18  	driver := state.Get("driver").(Driver)
    19  	containerId := state.Get("container_id").(string)
    20  	ui := state.Get("ui").(packer.Ui)
    21  
    22  	// We should catch this in validation, but guard anyway
    23  	if config.ExportPath == "" {
    24  		err := fmt.Errorf("No output file specified, we can't export anything")
    25  		state.Put("error", err)
    26  		ui.Error(err.Error())
    27  		return multistep.ActionHalt
    28  	}
    29  
    30  	// Make the directory we're exporting to if it doesn't exist
    31  	exportDir := filepath.Dir(config.ExportPath)
    32  	if err := os.MkdirAll(exportDir, 0755); err != nil {
    33  		state.Put("error", err)
    34  		return multistep.ActionHalt
    35  	}
    36  
    37  	// Open the file that we're going to write to
    38  	f, err := os.Create(config.ExportPath)
    39  	if err != nil {
    40  		err := fmt.Errorf("Error creating output file: %s", err)
    41  		state.Put("error", err)
    42  		ui.Error(err.Error())
    43  		return multistep.ActionHalt
    44  	}
    45  
    46  	ui.Say("Exporting the container")
    47  	if err := driver.Export(containerId, f); err != nil {
    48  		f.Close()
    49  		os.Remove(f.Name())
    50  
    51  		state.Put("error", err)
    52  		ui.Error(err.Error())
    53  		return multistep.ActionHalt
    54  	}
    55  
    56  	f.Close()
    57  	return multistep.ActionContinue
    58  }
    59  
    60  func (s *StepExport) Cleanup(state multistep.StateBag) {}