github.phpd.cn/hashicorp/packer@v1.3.2/builder/lxc/step_export.go (about)

     1  package lxc
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"log"
     8  	"os"
     9  	"os/user"
    10  	"path/filepath"
    11  
    12  	"github.com/hashicorp/packer/helper/multistep"
    13  	"github.com/hashicorp/packer/packer"
    14  )
    15  
    16  type stepExport struct{}
    17  
    18  func (s *stepExport) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    19  	config := state.Get("config").(*Config)
    20  	ui := state.Get("ui").(packer.Ui)
    21  
    22  	name := config.ContainerName
    23  
    24  	lxc_dir := "/var/lib/lxc"
    25  	user, err := user.Current()
    26  	if err != nil {
    27  		log.Print("Cannot find current user. Falling back to /var/lib/lxc...")
    28  	}
    29  	if user.Uid != "0" && user.HomeDir != "" {
    30  		lxc_dir = filepath.Join(user.HomeDir, ".local", "share", "lxc")
    31  	}
    32  
    33  	containerDir := filepath.Join(lxc_dir, name)
    34  	outputPath := filepath.Join(config.OutputDir, "rootfs.tar.gz")
    35  	configFilePath := filepath.Join(config.OutputDir, "lxc-config")
    36  
    37  	configFile, err := os.Create(configFilePath)
    38  
    39  	if err != nil {
    40  		err := fmt.Errorf("Error creating config file: %s", err)
    41  		state.Put("error", err)
    42  		ui.Error(err.Error())
    43  		return multistep.ActionHalt
    44  	}
    45  
    46  	originalConfigFile, err := os.Open(config.ConfigFile)
    47  
    48  	if err != nil {
    49  		err := fmt.Errorf("Error opening config file: %s", err)
    50  		state.Put("error", err)
    51  		ui.Error(err.Error())
    52  		return multistep.ActionHalt
    53  	}
    54  
    55  	_, err = io.Copy(configFile, originalConfigFile)
    56  
    57  	commands := make([][]string, 3)
    58  	commands[0] = []string{
    59  		"lxc-stop", "--name", name,
    60  	}
    61  	commands[1] = []string{
    62  		"tar", "-C", containerDir, "--numeric-owner", "--anchored", "--exclude=./rootfs/dev/log", "-czf", outputPath, "./rootfs",
    63  	}
    64  	commands[2] = []string{
    65  		"chmod", "+x", configFilePath,
    66  	}
    67  
    68  	ui.Say("Exporting container...")
    69  	for _, command := range commands {
    70  		err := RunCommand(command...)
    71  		if err != nil {
    72  			err := fmt.Errorf("Error exporting container: %s", err)
    73  			state.Put("error", err)
    74  			ui.Error(err.Error())
    75  			return multistep.ActionHalt
    76  		}
    77  	}
    78  
    79  	return multistep.ActionContinue
    80  }
    81  
    82  func (s *stepExport) Cleanup(state multistep.StateBag) {}