Files
Packer-Cn/builder/docker/step_connect_docker.go
T

83 lines
2.1 KiB
Go
Raw Normal View History

2013-11-08 23:43:41 -08:00
package docker
import (
2018-01-22 15:32:33 -08:00
"context"
"fmt"
"os/exec"
"strings"
2018-01-22 17:21:10 -08:00
2018-01-22 15:32:33 -08:00
"github.com/hashicorp/packer/helper/multistep"
2013-11-08 23:43:41 -08:00
)
type StepConnectDocker struct{}
2013-11-08 23:43:41 -08:00
func (s *StepConnectDocker) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config, ok := state.Get("config").(*Config)
if !ok {
err := fmt.Errorf("error encountered obtaining docker config")
state.Put("error", err)
return multistep.ActionHalt
}
2013-11-08 23:43:41 -08:00
containerId := state.Get("container_id").(string)
2015-05-29 09:29:59 -07:00
driver := state.Get("driver").(Driver)
2013-11-08 23:43:41 -08:00
tempDir := state.Get("temp_dir").(string)
2015-05-29 09:29:59 -07:00
// Get the version so we can pass it to the communicator
version, err := driver.Version()
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
containerUser, err := getContainerUser(containerId)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
2013-11-08 23:43:41 -08:00
// Create the communicator that talks to Docker via various
// os/exec tricks.
2019-03-27 14:51:50 -07:00
if config.WindowsContainer {
comm := &WindowsContainerCommunicator{Communicator{
2019-03-27 14:51:50 -07:00
ContainerID: containerId,
HostDir: tempDir,
ContainerDir: config.ContainerDir,
Version: version,
Config: config,
ContainerUser: containerUser,
2019-03-29 11:14:01 -07:00
EntryPoint: []string{"powershell"},
},
2019-03-27 14:51:50 -07:00
}
state.Put("communicator", comm)
2013-11-08 23:43:41 -08:00
2019-03-27 14:51:50 -07:00
} else {
comm := &Communicator{
ContainerID: containerId,
HostDir: tempDir,
ContainerDir: config.ContainerDir,
Version: version,
Config: config,
ContainerUser: containerUser,
2019-03-29 11:14:01 -07:00
EntryPoint: []string{"/bin/sh", "-c"},
2019-03-27 14:51:50 -07:00
}
state.Put("communicator", comm)
}
return multistep.ActionContinue
2013-11-08 23:43:41 -08:00
}
func (s *StepConnectDocker) Cleanup(state multistep.StateBag) {}
func getContainerUser(containerId string) (string, error) {
inspectArgs := []string{"docker", "inspect", "--format", "{{.Config.User}}", containerId}
stdout, err := exec.Command(inspectArgs[0], inspectArgs[1:]...).Output()
if err != nil {
errStr := fmt.Sprintf("Failed to inspect the container: %s", err)
if ee, ok := err.(*exec.ExitError); ok {
errStr = fmt.Sprintf("%s, %s", errStr, ee.Stderr)
}
return "", fmt.Errorf(errStr)
}
return strings.TrimSpace(string(stdout)), nil
}