2015-09-03 10:38:36 +00:00
|
|
|
package driver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2015-11-05 18:47:41 +00:00
|
|
|
"net"
|
2015-10-15 23:40:07 +00:00
|
|
|
"path/filepath"
|
2015-09-24 02:29:53 +00:00
|
|
|
"strconv"
|
2015-09-03 10:38:36 +00:00
|
|
|
"strings"
|
|
|
|
|
2015-09-08 19:43:02 +00:00
|
|
|
docker "github.com/fsouza/go-dockerclient"
|
|
|
|
|
2015-10-15 23:40:07 +00:00
|
|
|
"github.com/hashicorp/nomad/client/allocdir"
|
2015-09-03 10:38:36 +00:00
|
|
|
"github.com/hashicorp/nomad/client/config"
|
2015-10-15 23:40:07 +00:00
|
|
|
"github.com/hashicorp/nomad/client/driver/args"
|
2015-11-05 21:46:02 +00:00
|
|
|
"github.com/hashicorp/nomad/client/fingerprint"
|
2015-09-03 10:38:36 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DockerDriver struct {
|
2015-09-10 01:06:23 +00:00
|
|
|
DriverContext
|
2015-11-05 21:46:02 +00:00
|
|
|
fingerprint.StaticFingerprinter
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type dockerPID struct {
|
2015-09-04 04:00:16 +00:00
|
|
|
ImageID string
|
|
|
|
ContainerID string
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type dockerHandle struct {
|
2015-09-27 20:59:38 +00:00
|
|
|
client *docker.Client
|
|
|
|
logger *log.Logger
|
|
|
|
cleanupContainer bool
|
|
|
|
cleanupImage bool
|
|
|
|
imageID string
|
|
|
|
containerID string
|
|
|
|
waitCh chan error
|
|
|
|
doneCh chan struct{}
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
2015-09-10 01:06:23 +00:00
|
|
|
func NewDockerDriver(ctx *DriverContext) Driver {
|
2015-11-05 21:46:02 +00:00
|
|
|
return &DockerDriver{DriverContext: *ctx}
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
2015-10-07 00:53:05 +00:00
|
|
|
// dockerClient creates *docker.Client. In test / dev mode we can use ENV vars
|
|
|
|
// to connect to the docker daemon. In production mode we will read
|
|
|
|
// docker.endpoint from the config file.
|
2015-10-06 23:26:31 +00:00
|
|
|
func (d *DockerDriver) dockerClient() (*docker.Client, error) {
|
2015-10-07 00:53:05 +00:00
|
|
|
// In dev mode, read DOCKER_* environment variables DOCKER_HOST,
|
|
|
|
// DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH. This allows you to run tests and
|
|
|
|
// demo against boot2docker or a VM on OSX and Windows. This falls back on
|
|
|
|
// the default unix socket on linux if tests are run on linux.
|
|
|
|
//
|
|
|
|
// Also note that we need to turn on DevMode in the test configs.
|
|
|
|
if d.config.DevMode {
|
|
|
|
return docker.NewClientFromEnv()
|
|
|
|
}
|
|
|
|
|
|
|
|
// In prod mode we'll read the docker.endpoint configuration and fall back
|
|
|
|
// on the host-specific default. We do not read from the environment.
|
2015-10-08 19:35:19 +00:00
|
|
|
defaultEndpoint, err := docker.DefaultDockerHost()
|
2015-10-07 00:53:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to determine default docker endpoint: %s", err)
|
|
|
|
}
|
|
|
|
dockerEndpoint := d.config.ReadDefault("docker.endpoint", defaultEndpoint)
|
|
|
|
|
|
|
|
return docker.NewClient(dockerEndpoint)
|
2015-10-06 23:26:31 +00:00
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
|
2015-09-26 06:13:40 +00:00
|
|
|
// Initialize docker API client
|
2015-09-28 23:54:32 +00:00
|
|
|
client, err := d.dockerClient()
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2015-09-28 23:54:32 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: could not connect to docker daemon: %v", err)
|
2015-09-03 10:38:36 +00:00
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2015-11-06 01:57:51 +00:00
|
|
|
privileged, err := strconv.ParseBool(d.config.ReadDefault("docker.privileged.enabled", "false"))
|
2015-11-06 00:40:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("Unable to parse docker.privileged.enabled: %s", err)
|
|
|
|
}
|
|
|
|
if privileged == true {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: privileged containers enabled. Only enable if needed")
|
|
|
|
node.Attributes["docker.privileged.enabled"] = "1"
|
|
|
|
}
|
|
|
|
|
2015-09-27 20:59:38 +00:00
|
|
|
_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
|
2015-09-27 01:53:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
|
|
|
|
}
|
2015-09-27 20:59:38 +00:00
|
|
|
_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
|
2015-09-27 01:53:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-09-26 06:13:40 +00:00
|
|
|
env, err := client.Version()
|
2015-09-26 06:55:01 +00:00
|
|
|
if err != nil {
|
2015-09-28 23:54:32 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: could not read version from daemon: %v", err)
|
2015-09-27 21:59:21 +00:00
|
|
|
// Check the "no such file" error if the unix file is missing
|
|
|
|
if strings.Contains(err.Error(), "no such file") {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2015-09-26 06:55:01 +00:00
|
|
|
// We connected to the daemon but couldn't read the version so something
|
|
|
|
// is broken.
|
|
|
|
return false, err
|
2015-09-26 06:13:40 +00:00
|
|
|
}
|
2015-10-12 20:15:37 +00:00
|
|
|
node.Attributes["driver.docker"] = "1"
|
2015-09-26 06:55:01 +00:00
|
|
|
node.Attributes["driver.docker.version"] = env.Get("Version")
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2015-10-16 00:47:14 +00:00
|
|
|
func (d *DockerDriver) containerBinds(alloc *allocdir.AllocDir, task *structs.Task) ([]string, error) {
|
2015-10-15 23:40:07 +00:00
|
|
|
shared := alloc.SharedDir
|
|
|
|
local, ok := alloc.TaskDirs[task.Name]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("Failed to find task local directory: %v", task.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
return []string{
|
2015-11-03 14:40:24 +00:00
|
|
|
// "z" and "Z" option is to allocate directory with SELinux label.
|
|
|
|
fmt.Sprintf("%s:/%s:rw,z", shared, allocdir.SharedAllocName),
|
|
|
|
// capital "Z" will label with Multi-Category Security (MCS) labels
|
|
|
|
fmt.Sprintf("%s:/%s:rw,Z", local, allocdir.TaskLocal),
|
2015-10-15 23:40:07 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// createContainer initializes a struct needed to call docker.client.CreateContainer()
|
2015-10-16 00:47:14 +00:00
|
|
|
func (d *DockerDriver) createContainer(ctx *ExecContext, task *structs.Task) (docker.CreateContainerOptions, error) {
|
2015-10-15 23:40:07 +00:00
|
|
|
var c docker.CreateContainerOptions
|
|
|
|
if task.Resources == nil {
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[ERR] driver.docker: task.Resources is empty")
|
2015-10-15 23:40:07 +00:00
|
|
|
return c, fmt.Errorf("task.Resources is nil and we can't constrain resource usage. We shouldn't have been able to schedule this in the first place.")
|
|
|
|
}
|
|
|
|
|
2015-10-16 00:47:14 +00:00
|
|
|
binds, err := d.containerBinds(ctx.AllocDir, task)
|
2015-10-15 23:40:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return c, err
|
|
|
|
}
|
|
|
|
|
|
|
|
hostConfig := &docker.HostConfig{
|
2015-09-09 08:08:31 +00:00
|
|
|
// Convert MB to bytes. This is an absolute value.
|
|
|
|
//
|
|
|
|
// This value represents the total amount of memory a process can use.
|
|
|
|
// Swap is added to total memory and is managed by the OS, not docker.
|
|
|
|
// Since this may cause other processes to swap and cause system
|
|
|
|
// instability, we will simply not use swap.
|
|
|
|
//
|
|
|
|
// See: https://www.kernel.org/doc/Documentation/cgroups/memory.txt
|
|
|
|
Memory: int64(task.Resources.MemoryMB) * 1024 * 1024,
|
|
|
|
MemorySwap: -1,
|
|
|
|
// Convert Mhz to shares. This is a relative value.
|
|
|
|
//
|
|
|
|
// There are two types of CPU limiters available: Shares and Quotas. A
|
|
|
|
// Share allows a particular process to have a proportion of CPU time
|
|
|
|
// relative to other processes; 1024 by default. A CPU Quota is enforced
|
|
|
|
// over a Period of time and is a HARD limit on the amount of CPU time a
|
|
|
|
// process can use. Processes with quotas cannot burst, while processes
|
|
|
|
// with shares can, so we'll use shares.
|
|
|
|
//
|
|
|
|
// The simplest scale is 1 share to 1 MHz so 1024 = 1GHz. This means any
|
|
|
|
// given process will have at least that amount of resources, but likely
|
|
|
|
// more since it is (probably) rare that the machine will run at 100%
|
|
|
|
// CPU. This scale will cease to work if a node is overprovisioned.
|
|
|
|
//
|
|
|
|
// See:
|
|
|
|
// - https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
|
|
|
|
// - https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt
|
|
|
|
CPUShares: int64(task.Resources.CPU),
|
2015-09-26 01:22:10 +00:00
|
|
|
|
2015-10-15 23:40:07 +00:00
|
|
|
// Binds are used to mount a host volume into the container. We mount a
|
|
|
|
// local directory for storage and a shared alloc directory that can be
|
|
|
|
// used to share data between different tasks in the same task group.
|
|
|
|
Binds: binds,
|
2015-09-26 01:22:10 +00:00
|
|
|
}
|
|
|
|
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %d bytes memory for %s", hostConfig.Memory, task.Config["image"])
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %d cpu shares for %s", hostConfig.CPUShares, task.Config["image"])
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: binding directories %#v for %s", hostConfig.Binds, task.Config["image"])
|
2015-09-09 08:08:31 +00:00
|
|
|
|
2015-11-06 00:40:20 +00:00
|
|
|
// set privileged mode
|
|
|
|
if v, ok := task.Config["privileged"]; ok {
|
|
|
|
taskPrivileged, err := strconv.ParseBool(v)
|
|
|
|
if err != nil {
|
2015-11-06 01:57:51 +00:00
|
|
|
return c, fmt.Errorf("Unable to parse boolean value from task config option 'privileged': %s", err)
|
2015-11-06 00:40:20 +00:00
|
|
|
}
|
|
|
|
hostConfig.Privileged = taskPrivileged
|
|
|
|
}
|
2015-11-05 18:47:41 +00:00
|
|
|
|
|
|
|
// set DNS servers
|
|
|
|
dns, ok := task.Config["dns-servers"]
|
|
|
|
|
|
|
|
if ok && dns != "" {
|
|
|
|
for _, v := range strings.Split(dns, ",") {
|
|
|
|
ip := strings.TrimSpace(v)
|
|
|
|
if net.ParseIP(ip) != nil {
|
|
|
|
hostConfig.DNS = append(hostConfig.DNS, ip)
|
|
|
|
} else {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: invalid ip address for container dns server: %s", ip)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// set DNS search domains
|
|
|
|
dnsSearch, ok := task.Config["search-domains"]
|
|
|
|
|
|
|
|
if ok && dnsSearch != "" {
|
|
|
|
for _, v := range strings.Split(dnsSearch, ",") {
|
|
|
|
hostConfig.DNSSearch = append(hostConfig.DNSSearch, strings.TrimSpace(v))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-10-01 02:15:24 +00:00
|
|
|
mode, ok := task.Config["network_mode"]
|
2015-10-02 17:54:04 +00:00
|
|
|
if !ok || mode == "" {
|
|
|
|
// docker default
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[WARN] driver.docker: no mode specified for networking, defaulting to bridge")
|
2015-10-02 17:54:04 +00:00
|
|
|
mode = "bridge"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ignore the container mode for now
|
|
|
|
switch mode {
|
|
|
|
case "default", "bridge", "none", "host":
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %s as network mode", mode)
|
2015-10-02 17:54:04 +00:00
|
|
|
default:
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[ERR] driver.docker: invalid setting for network mode: %s", mode)
|
2015-10-13 06:57:16 +00:00
|
|
|
return c, fmt.Errorf("Invalid setting for network mode: %s", mode)
|
2015-10-02 17:54:04 +00:00
|
|
|
}
|
2015-10-01 02:15:24 +00:00
|
|
|
hostConfig.NetworkMode = mode
|
|
|
|
|
2015-09-24 01:01:08 +00:00
|
|
|
// Setup port mapping (equivalent to -p on docker CLI). Ports must already be
|
|
|
|
// exposed in the container.
|
|
|
|
if len(task.Resources.Networks) == 0 {
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Print("[WARN] driver.docker: No networks are available for port mapping")
|
2015-09-24 01:01:08 +00:00
|
|
|
} else {
|
|
|
|
network := task.Resources.Networks[0]
|
|
|
|
dockerPorts := map[docker.Port][]docker.PortBinding{}
|
|
|
|
|
2015-09-24 06:45:34 +00:00
|
|
|
for _, port := range network.ListStaticPorts() {
|
|
|
|
dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
|
|
|
dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (static)\n", network.IP, port, port)
|
2015-09-24 06:45:34 +00:00
|
|
|
}
|
|
|
|
|
2015-09-24 01:01:08 +00:00
|
|
|
for label, port := range network.MapDynamicPorts() {
|
2015-09-24 01:19:01 +00:00
|
|
|
// If the label is numeric we expect that there is a service
|
|
|
|
// listening on that port inside the container. In this case we'll
|
|
|
|
// setup a mapping from our random host port to the label port.
|
|
|
|
//
|
|
|
|
// Otherwise we'll setup a direct 1:1 mapping from the host port to
|
|
|
|
// the container, and assume that the process inside will read the
|
|
|
|
// environment variable and bind to the correct port.
|
2015-09-26 06:55:01 +00:00
|
|
|
if _, err := strconv.Atoi(label); err == nil {
|
2015-09-24 02:29:53 +00:00
|
|
|
dockerPorts[docker.Port(label+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
|
|
|
dockerPorts[docker.Port(label+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %s (mapped)", network.IP, port, label)
|
2015-09-24 01:19:01 +00:00
|
|
|
} else {
|
2015-09-24 02:29:53 +00:00
|
|
|
dockerPorts[docker.Port(strconv.Itoa(port)+"/tcp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
|
|
|
dockerPorts[docker.Port(strconv.Itoa(port)+"/udp")] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: strconv.Itoa(port)}}
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d for label %s\n", network.IP, port, port, label)
|
2015-09-24 01:01:08 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-24 06:57:04 +00:00
|
|
|
hostConfig.PortBindings = dockerPorts
|
2015-09-24 01:01:08 +00:00
|
|
|
}
|
|
|
|
|
2015-10-15 23:40:07 +00:00
|
|
|
// Create environment variables.
|
|
|
|
env := TaskEnvironmentVariables(ctx, task)
|
|
|
|
env.SetAllocDir(filepath.Join("/", allocdir.SharedAllocName))
|
|
|
|
env.SetTaskLocalDir(filepath.Join("/", allocdir.TaskLocal))
|
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
config := &docker.Config{
|
2015-10-15 23:40:07 +00:00
|
|
|
Env: env.List(),
|
2015-09-26 01:22:10 +00:00
|
|
|
Image: task.Config["image"],
|
|
|
|
}
|
|
|
|
|
2015-10-15 23:40:07 +00:00
|
|
|
rawArgs, hasArgs := task.Config["args"]
|
|
|
|
parsedArgs, err := args.ParseAndReplace(rawArgs, env.Map())
|
|
|
|
if err != nil {
|
|
|
|
return c, err
|
|
|
|
}
|
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
// If the user specified a custom command to run, we'll inject it here.
|
|
|
|
if command, ok := task.Config["command"]; ok {
|
2015-10-15 23:40:07 +00:00
|
|
|
cmd := []string{command}
|
|
|
|
if hasArgs {
|
|
|
|
cmd = append(cmd, parsedArgs...)
|
|
|
|
}
|
|
|
|
config.Cmd = cmd
|
|
|
|
} else if hasArgs {
|
2015-10-16 00:47:14 +00:00
|
|
|
d.logger.Println("[DEBUG] driver.docker: ignoring args because command not specified")
|
2015-09-26 01:22:10 +00:00
|
|
|
}
|
|
|
|
|
2015-09-09 08:08:31 +00:00
|
|
|
return docker.CreateContainerOptions{
|
2015-09-26 01:22:10 +00:00
|
|
|
Config: config,
|
2015-09-24 06:57:04 +00:00
|
|
|
HostConfig: hostConfig,
|
2015-10-13 06:57:16 +00:00
|
|
|
}, nil
|
2015-09-09 08:08:31 +00:00
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
func (d *DockerDriver) Start(ctx *ExecContext, task *structs.Task) (DriverHandle, error) {
|
|
|
|
// Get the image from config
|
|
|
|
image, ok := task.Config["image"]
|
|
|
|
if !ok || image == "" {
|
|
|
|
return nil, fmt.Errorf("Image not specified")
|
|
|
|
}
|
2015-09-09 08:08:31 +00:00
|
|
|
if task.Resources == nil {
|
|
|
|
return nil, fmt.Errorf("Resources are not specified")
|
|
|
|
}
|
2015-09-09 20:35:10 +00:00
|
|
|
if task.Resources.MemoryMB == 0 {
|
|
|
|
return nil, fmt.Errorf("Memory limit cannot be zero")
|
|
|
|
}
|
|
|
|
if task.Resources.CPU == 0 {
|
2015-09-10 18:35:03 +00:00
|
|
|
return nil, fmt.Errorf("CPU limit cannot be zero")
|
2015-09-09 20:35:10 +00:00
|
|
|
}
|
2015-09-09 08:08:31 +00:00
|
|
|
|
2015-09-27 20:59:38 +00:00
|
|
|
cleanupContainer, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
|
|
|
|
}
|
|
|
|
cleanupImage, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-09-09 08:08:31 +00:00
|
|
|
// Initialize docker API client
|
2015-09-28 23:54:32 +00:00
|
|
|
client, err := d.dockerClient()
|
2015-09-09 08:08:31 +00:00
|
|
|
if err != nil {
|
2015-10-07 02:09:59 +00:00
|
|
|
return nil, fmt.Errorf("Failed to connect to docker daemon: %s", err)
|
2015-09-09 08:08:31 +00:00
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
repo, tag := docker.ParseRepositoryTag(image)
|
|
|
|
// Make sure tag is always explicitly set. We'll default to "latest" if it
|
|
|
|
// isn't, which is the expected behavior.
|
|
|
|
if tag == "" {
|
|
|
|
tag = "latest"
|
|
|
|
}
|
|
|
|
|
|
|
|
var dockerImage *docker.Image
|
|
|
|
// We're going to check whether the image is already downloaded. If the tag
|
2015-09-26 06:28:23 +00:00
|
|
|
// is "latest" we have to check for a new version every time so we don't
|
|
|
|
// bother to check and cache the id here. We'll download first, then cache.
|
2015-09-26 01:22:10 +00:00
|
|
|
if tag != "latest" {
|
|
|
|
dockerImage, err = client.InspectImage(image)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
// Download the image
|
|
|
|
if dockerImage == nil {
|
|
|
|
pullOptions := docker.PullImageOptions{
|
|
|
|
Repository: repo,
|
|
|
|
Tag: tag,
|
|
|
|
}
|
2015-11-05 18:47:41 +00:00
|
|
|
|
|
|
|
authOptions := docker.AuthConfiguration{
|
|
|
|
Username: task.Config["auth.username"],
|
|
|
|
Password: task.Config["auth.password"],
|
|
|
|
Email: task.Config["auth.email"],
|
|
|
|
ServerAddress: task.Config["auth.server-address"],
|
|
|
|
}
|
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
err = client.PullImage(pullOptions, authOptions)
|
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: pulling container %s", err)
|
|
|
|
return nil, fmt.Errorf("Failed to pull `%s`: %s", image, err)
|
|
|
|
}
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: docker pull %s:%s succeeded", repo, tag)
|
|
|
|
|
|
|
|
// Now that we have the image we can get the image id
|
|
|
|
dockerImage, err = client.InspectImage(image)
|
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: getting image id for %s", image)
|
|
|
|
return nil, fmt.Errorf("Failed to determine image id for `%s`: %s", image, err)
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
2015-09-26 01:22:10 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using image %s", dockerImage.ID)
|
|
|
|
d.logger.Printf("[INFO] driver.docker: identified image %s as %s", image, dockerImage.ID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
2015-10-16 00:47:14 +00:00
|
|
|
config, err := d.createContainer(ctx, task)
|
2015-10-13 23:21:16 +00:00
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: %s", err)
|
|
|
|
return nil, fmt.Errorf("Failed to create container config for image %s", image)
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
// Create a container
|
2015-10-13 06:57:16 +00:00
|
|
|
container, err := client.CreateContainer(config)
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2015-09-11 17:26:33 +00:00
|
|
|
d.logger.Printf("[ERR] driver.docker: %s", err)
|
2015-09-03 10:38:36 +00:00
|
|
|
return nil, fmt.Errorf("Failed to create container from image %s", image)
|
|
|
|
}
|
2015-09-09 20:35:10 +00:00
|
|
|
d.logger.Printf("[INFO] driver.docker: created container %s", container.ID)
|
2015-09-08 19:43:02 +00:00
|
|
|
|
2015-09-09 08:08:31 +00:00
|
|
|
// Start the container
|
2015-10-02 17:43:37 +00:00
|
|
|
err = client.StartContainer(container.ID, container.HostConfig)
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2015-09-26 01:22:10 +00:00
|
|
|
d.logger.Printf("[ERR] driver.docker: starting container %s", container.ID)
|
2015-09-09 08:08:31 +00:00
|
|
|
return nil, fmt.Errorf("Failed to start container %s", container.ID)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
2015-09-09 20:35:10 +00:00
|
|
|
d.logger.Printf("[INFO] driver.docker: started container %s", container.ID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
|
|
// Return a driver handle
|
|
|
|
h := &dockerHandle{
|
2015-09-27 20:59:38 +00:00
|
|
|
client: client,
|
|
|
|
cleanupContainer: cleanupContainer,
|
|
|
|
cleanupImage: cleanupImage,
|
|
|
|
logger: d.logger,
|
|
|
|
imageID: dockerImage.ID,
|
|
|
|
containerID: container.ID,
|
|
|
|
doneCh: make(chan struct{}),
|
|
|
|
waitCh: make(chan error, 1),
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
2015-09-04 04:00:16 +00:00
|
|
|
go h.run()
|
2015-09-03 10:38:36 +00:00
|
|
|
return h, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *DockerDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
|
2015-09-27 20:59:38 +00:00
|
|
|
cleanupContainer, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
|
|
|
|
}
|
|
|
|
cleanupImage, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
// Split the handle
|
2015-09-04 04:00:16 +00:00
|
|
|
pidBytes := []byte(strings.TrimPrefix(handleID, "DOCKER:"))
|
2015-09-03 10:38:36 +00:00
|
|
|
pid := &dockerPID{}
|
2015-09-27 20:59:38 +00:00
|
|
|
err = json.Unmarshal(pidBytes, pid)
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
|
|
|
|
}
|
2015-09-09 20:35:10 +00:00
|
|
|
d.logger.Printf("[INFO] driver.docker: re-attaching to docker process: %s", handleID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
2015-09-26 03:01:03 +00:00
|
|
|
// Initialize docker API client
|
2015-09-28 23:54:32 +00:00
|
|
|
client, err := d.dockerClient()
|
2015-09-26 03:01:03 +00:00
|
|
|
if err != nil {
|
2015-10-07 02:09:59 +00:00
|
|
|
return nil, fmt.Errorf("Failed to connect to docker daemon: %s", err)
|
2015-09-26 03:01:03 +00:00
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
// Look for a running container with this ID
|
2015-09-26 06:13:40 +00:00
|
|
|
containers, err := client.ListContainers(docker.ListContainersOptions{
|
|
|
|
Filters: map[string][]string{
|
|
|
|
"id": []string{pid.ContainerID},
|
|
|
|
},
|
|
|
|
})
|
2015-09-04 04:00:16 +00:00
|
|
|
if err != nil {
|
2015-09-26 06:13:40 +00:00
|
|
|
return nil, fmt.Errorf("Failed to query for container %s: %v", pid.ContainerID, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
found := false
|
|
|
|
for _, container := range containers {
|
|
|
|
if container.ID == pid.ContainerID {
|
|
|
|
found = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !found {
|
2015-09-04 04:00:16 +00:00
|
|
|
return nil, fmt.Errorf("Failed to find container %s: %v", pid.ContainerID, err)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return a driver handle
|
|
|
|
h := &dockerHandle{
|
2015-09-27 20:59:38 +00:00
|
|
|
client: client,
|
|
|
|
cleanupContainer: cleanupContainer,
|
|
|
|
cleanupImage: cleanupImage,
|
|
|
|
logger: d.logger,
|
|
|
|
imageID: pid.ImageID,
|
|
|
|
containerID: pid.ContainerID,
|
|
|
|
doneCh: make(chan struct{}),
|
|
|
|
waitCh: make(chan error, 1),
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
go h.run()
|
|
|
|
return h, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *dockerHandle) ID() string {
|
|
|
|
// Return a handle to the PID
|
|
|
|
pid := dockerPID{
|
2015-09-04 04:00:16 +00:00
|
|
|
ImageID: h.imageID,
|
|
|
|
ContainerID: h.containerID,
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
data, err := json.Marshal(pid)
|
|
|
|
if err != nil {
|
2015-09-11 17:26:33 +00:00
|
|
|
h.logger.Printf("[ERR] driver.docker: failed to marshal docker PID to JSON: %s", err)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
return fmt.Sprintf("DOCKER:%s", string(data))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *dockerHandle) WaitCh() chan error {
|
|
|
|
return h.waitCh
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *dockerHandle) Update(task *structs.Task) error {
|
|
|
|
// Update is not possible
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-09-04 04:00:16 +00:00
|
|
|
// Kill is used to terminate the task. This uses docker stop -t 5
|
2015-09-03 10:38:36 +00:00
|
|
|
func (h *dockerHandle) Kill() error {
|
|
|
|
// Stop the container
|
2015-09-26 03:01:03 +00:00
|
|
|
err := h.client.StopContainer(h.containerID, 5)
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2015-09-26 05:43:19 +00:00
|
|
|
log.Printf("[ERR] driver.docker: failed stopping container %s", h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
return fmt.Errorf("Failed to stop container %s: %s", h.containerID, err)
|
|
|
|
}
|
2015-09-09 20:35:10 +00:00
|
|
|
log.Printf("[INFO] driver.docker: stopped container %s", h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
|
|
// Cleanup container
|
2015-09-27 20:59:38 +00:00
|
|
|
if h.cleanupContainer {
|
2015-09-27 01:53:15 +00:00
|
|
|
err = h.client.RemoveContainer(docker.RemoveContainerOptions{
|
|
|
|
ID: h.containerID,
|
|
|
|
RemoveVolumes: true,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("[ERR] driver.docker: removing container %s", h.containerID)
|
|
|
|
return fmt.Errorf("Failed to remove container %s: %s", h.containerID, err)
|
|
|
|
}
|
|
|
|
log.Printf("[INFO] driver.docker: removed container %s", h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Cleanup image. This operation may fail if the image is in use by another
|
|
|
|
// job. That is OK. Will we log a message but continue.
|
2015-09-27 20:59:38 +00:00
|
|
|
if h.cleanupImage {
|
2015-09-27 01:53:15 +00:00
|
|
|
err = h.client.RemoveImage(h.imageID)
|
2015-09-26 07:34:57 +00:00
|
|
|
if err != nil {
|
2015-09-27 01:53:15 +00:00
|
|
|
containers, err := h.client.ListContainers(docker.ListContainersOptions{
|
2015-10-07 00:53:05 +00:00
|
|
|
// The image might be in use by a stopped container, so check everything
|
2015-09-27 04:52:02 +00:00
|
|
|
All: true,
|
2015-09-27 01:53:15 +00:00
|
|
|
Filters: map[string][]string{
|
|
|
|
"image": []string{h.imageID},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Unable to query list of containers: %s", err)
|
|
|
|
}
|
|
|
|
inUse := len(containers)
|
|
|
|
if inUse > 0 {
|
|
|
|
log.Printf("[INFO] driver.docker: image %s is still in use by %d containers", h.imageID, inUse)
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("Failed to remove image %s", h.imageID)
|
|
|
|
}
|
2015-09-26 07:34:57 +00:00
|
|
|
} else {
|
2015-09-27 01:53:15 +00:00
|
|
|
log.Printf("[INFO] driver.docker: removed image %s", h.imageID)
|
2015-09-26 07:34:57 +00:00
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *dockerHandle) run() {
|
|
|
|
// Wait for it...
|
2015-09-26 05:43:19 +00:00
|
|
|
exitCode, err := h.client.WaitContainer(h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2015-09-11 17:26:33 +00:00
|
|
|
h.logger.Printf("[ERR] driver.docker: unable to wait for %s; container already terminated", h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
|
|
|
|
2015-09-26 05:43:19 +00:00
|
|
|
if exitCode != 0 {
|
|
|
|
err = fmt.Errorf("Docker container exited with non-zero exit code: %d", exitCode)
|
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
close(h.doneCh)
|
|
|
|
if err != nil {
|
|
|
|
h.waitCh <- err
|
|
|
|
}
|
|
|
|
close(h.waitCh)
|
|
|
|
}
|