2015-09-03 10:38:36 +00:00
|
|
|
|
package driver
|
|
|
|
|
|
|
|
|
|
import (
|
2017-02-01 00:43:57 +00:00
|
|
|
|
"context"
|
2015-09-03 10:38:36 +00:00
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log"
|
2015-11-05 18:47:41 +00:00
|
|
|
|
"net"
|
2016-02-06 13:43:30 +00:00
|
|
|
|
"os"
|
2017-05-29 10:44:13 +00:00
|
|
|
|
"os/exec"
|
2015-10-15 23:40:07 +00:00
|
|
|
|
"path/filepath"
|
2016-06-12 16:08:35 +00:00
|
|
|
|
"runtime"
|
2015-09-24 02:29:53 +00:00
|
|
|
|
"strconv"
|
2015-09-03 10:38:36 +00:00
|
|
|
|
"strings"
|
2015-12-10 21:49:29 +00:00
|
|
|
|
"sync"
|
2016-10-07 19:37:52 +00:00
|
|
|
|
"syscall"
|
2015-12-23 00:10:30 +00:00
|
|
|
|
"time"
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
2017-02-01 00:43:57 +00:00
|
|
|
|
"github.com/armon/circbuf"
|
2015-09-08 19:43:02 +00:00
|
|
|
|
docker "github.com/fsouza/go-dockerclient"
|
|
|
|
|
|
2017-01-12 19:22:35 +00:00
|
|
|
|
"github.com/docker/docker/cli/config/configfile"
|
|
|
|
|
"github.com/docker/docker/reference"
|
|
|
|
|
"github.com/docker/docker/registry"
|
|
|
|
|
|
2016-03-31 00:21:07 +00:00
|
|
|
|
"github.com/hashicorp/go-multierror"
|
2016-02-10 02:24:30 +00:00
|
|
|
|
"github.com/hashicorp/go-plugin"
|
2015-10-15 23:40:07 +00:00
|
|
|
|
"github.com/hashicorp/nomad/client/allocdir"
|
2016-11-08 22:18:40 +00:00
|
|
|
|
"github.com/hashicorp/nomad/client/driver/env"
|
2016-03-17 09:53:31 +00:00
|
|
|
|
"github.com/hashicorp/nomad/client/driver/executor"
|
2016-06-12 03:15:50 +00:00
|
|
|
|
dstructs "github.com/hashicorp/nomad/client/driver/structs"
|
|
|
|
|
cstructs "github.com/hashicorp/nomad/client/structs"
|
2017-02-21 03:35:51 +00:00
|
|
|
|
"github.com/hashicorp/nomad/helper"
|
2016-04-09 22:38:42 +00:00
|
|
|
|
"github.com/hashicorp/nomad/helper/fields"
|
2016-06-10 21:32:45 +00:00
|
|
|
|
shelpers "github.com/hashicorp/nomad/helper/stats"
|
2015-09-03 10:38:36 +00:00
|
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2015-11-14 02:09:42 +00:00
|
|
|
|
"github.com/mitchellh/mapstructure"
|
2015-09-03 10:38:36 +00:00
|
|
|
|
)
|
|
|
|
|
|
2016-03-03 00:27:01 +00:00
|
|
|
|
var (
|
2018-04-05 16:21:29 +00:00
|
|
|
|
// createClientsLock is a lock that protects reading/writing global client
|
|
|
|
|
// variables
|
|
|
|
|
createClientsLock sync.Mutex
|
|
|
|
|
|
2018-04-03 20:34:50 +00:00
|
|
|
|
// client is a docker client with a timeout of 5 minutes. This is for doing
|
2016-06-11 18:34:41 +00:00
|
|
|
|
// all operations with the docker daemon besides which are not long running
|
|
|
|
|
// such as creating, killing containers, etc.
|
|
|
|
|
client *docker.Client
|
|
|
|
|
|
|
|
|
|
// waitClient is a docker client with no timeouts. This is used for long
|
|
|
|
|
// running operations such as waiting on containers and collect stats
|
|
|
|
|
waitClient *docker.Client
|
2016-06-10 02:45:41 +00:00
|
|
|
|
|
2018-04-03 20:55:46 +00:00
|
|
|
|
// healthCheckClient is a docker client with a timeout of 1 minute. This is
|
|
|
|
|
// necessary to have a shorter timeout than other API or fingerprint calls
|
|
|
|
|
healthCheckClient *docker.Client
|
|
|
|
|
|
2016-06-10 02:45:41 +00:00
|
|
|
|
// The statistics the Docker driver exposes
|
2016-06-10 17:38:29 +00:00
|
|
|
|
DockerMeasuredMemStats = []string{"RSS", "Cache", "Swap", "Max Usage"}
|
|
|
|
|
DockerMeasuredCpuStats = []string{"Throttled Periods", "Throttled Time", "Percent"}
|
2016-11-30 23:59:47 +00:00
|
|
|
|
|
|
|
|
|
// recoverableErrTimeouts returns a recoverable error if the error was due
|
|
|
|
|
// to timeouts
|
2017-01-14 00:46:08 +00:00
|
|
|
|
recoverableErrTimeouts = func(err error) error {
|
2016-11-30 23:59:47 +00:00
|
|
|
|
r := false
|
|
|
|
|
if strings.Contains(err.Error(), "Client.Timeout exceeded while awaiting headers") ||
|
2017-02-24 21:20:40 +00:00
|
|
|
|
strings.Contains(err.Error(), "EOF") {
|
2016-11-30 23:59:47 +00:00
|
|
|
|
r = true
|
|
|
|
|
}
|
|
|
|
|
return structs.NewRecoverableError(err, r)
|
|
|
|
|
}
|
2016-03-03 00:27:01 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
// NoSuchContainerError is returned by the docker daemon if the container
|
|
|
|
|
// does not exist.
|
|
|
|
|
NoSuchContainerError = "No such container"
|
2016-04-01 01:11:27 +00:00
|
|
|
|
|
|
|
|
|
// The key populated in Node Attributes to indicate presence of the Docker
|
|
|
|
|
// driver
|
|
|
|
|
dockerDriverAttr = "driver.docker"
|
2016-04-22 18:11:38 +00:00
|
|
|
|
|
2016-10-03 23:04:33 +00:00
|
|
|
|
// dockerSELinuxLabelConfigOption is the key for configuring the
|
|
|
|
|
// SELinux label for binds.
|
2016-09-27 20:13:55 +00:00
|
|
|
|
dockerSELinuxLabelConfigOption = "docker.volumes.selinuxlabel"
|
2016-10-03 23:04:33 +00:00
|
|
|
|
|
|
|
|
|
// dockerVolumesConfigOption is the key for enabling the use of custom
|
2016-10-20 21:00:27 +00:00
|
|
|
|
// bind volumes to arbitrary host paths.
|
2016-10-20 00:13:45 +00:00
|
|
|
|
dockerVolumesConfigOption = "docker.volumes.enabled"
|
|
|
|
|
dockerVolumesConfigDefault = true
|
2016-10-03 23:04:33 +00:00
|
|
|
|
|
|
|
|
|
// dockerPrivilegedConfigOption is the key for running containers in
|
|
|
|
|
// Docker's privileged mode.
|
|
|
|
|
dockerPrivilegedConfigOption = "docker.privileged.enabled"
|
2016-09-27 20:13:55 +00:00
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
|
// dockerCleanupImageConfigOption is the key for whether or not to
|
|
|
|
|
// cleanup images after the task exits.
|
|
|
|
|
dockerCleanupImageConfigOption = "docker.cleanup.image"
|
|
|
|
|
dockerCleanupImageConfigDefault = true
|
|
|
|
|
|
2017-02-24 21:20:40 +00:00
|
|
|
|
// dockerPullTimeoutConfigOption is the key for setting an images pull
|
|
|
|
|
// timeout
|
|
|
|
|
dockerImageRemoveDelayConfigOption = "docker.cleanup.image.delay"
|
|
|
|
|
dockerImageRemoveDelayConfigDefault = 3 * time.Minute
|
|
|
|
|
|
2018-01-21 11:14:24 +00:00
|
|
|
|
// dockerCapsWhitelistConfigOption is the key for setting the list of
|
|
|
|
|
// allowed Linux capabilities
|
2018-01-14 18:58:35 +00:00
|
|
|
|
dockerCapsWhitelistConfigOption = "docker.caps.whitelist"
|
|
|
|
|
dockerCapsWhitelistConfigDefault = dockerBasicCaps
|
|
|
|
|
|
2016-04-22 18:11:38 +00:00
|
|
|
|
// dockerTimeout is the length of time a request can be outstanding before
|
|
|
|
|
// it is timed out.
|
2016-11-30 23:59:47 +00:00
|
|
|
|
dockerTimeout = 5 * time.Minute
|
2017-01-10 21:24:45 +00:00
|
|
|
|
|
2018-04-03 20:55:46 +00:00
|
|
|
|
// dockerHealthCheckTimeout is the length of time a request for a health
|
|
|
|
|
// check client can be outstanding before it is timed out.
|
2018-04-05 16:21:29 +00:00
|
|
|
|
dockerHealthCheckTimeout = 1 * time.Minute
|
2018-04-03 20:55:46 +00:00
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
|
// dockerImageResKey is the CreatedResources key for docker images
|
|
|
|
|
dockerImageResKey = "image"
|
2017-05-29 10:44:13 +00:00
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// dockerAuthHelperPrefix is the prefix to attach to the credential helper
|
|
|
|
|
// and should be found in the $PATH. Example: ${prefix-}${helper-name}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
dockerAuthHelperPrefix = "docker-credential-"
|
2018-01-14 18:58:35 +00:00
|
|
|
|
|
2018-01-21 11:14:24 +00:00
|
|
|
|
// dockerBasicCaps is comma-separated list of Linux capabilities that are
|
|
|
|
|
// allowed by docker by default, as documented in
|
|
|
|
|
// https://docs.docker.com/engine/reference/run/#block-io-bandwidth-blkio-constraint
|
|
|
|
|
dockerBasicCaps = "CHOWN,DAC_OVERRIDE,FSETID,FOWNER,MKNOD,NET_RAW,SETGID," +
|
|
|
|
|
"SETUID,SETFCAP,SETPCAP,NET_BIND_SERVICE,SYS_CHROOT,KILL,AUDIT_WRITE"
|
2018-02-01 18:09:12 +00:00
|
|
|
|
|
2018-02-01 22:16:38 +00:00
|
|
|
|
// This is cpu.cfs_period_us: the length of a period.
|
2018-02-07 03:11:39 +00:00
|
|
|
|
// The default values is 100 milliseconds (ms) represented in microseconds (us).
|
2018-03-11 17:55:21 +00:00
|
|
|
|
// Below is the documentation:
|
2018-02-01 18:09:12 +00:00
|
|
|
|
// https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
|
2018-02-07 03:11:39 +00:00
|
|
|
|
// https://docs.docker.com/engine/api/v1.35/#
|
2018-02-08 00:28:43 +00:00
|
|
|
|
defaultCFSPeriodUS = 100000
|
2016-03-03 00:27:01 +00:00
|
|
|
|
)
|
2015-12-10 21:49:29 +00:00
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
type DockerDriver struct {
|
2015-09-10 01:06:23 +00:00
|
|
|
|
DriverContext
|
2016-11-30 00:39:36 +00:00
|
|
|
|
|
|
|
|
|
driverConfig *DockerDriverConfig
|
2017-01-13 20:46:55 +00:00
|
|
|
|
imageID string
|
2017-02-21 03:35:51 +00:00
|
|
|
|
|
|
|
|
|
// A tri-state boolean to know if the fingerprinting has happened and
|
|
|
|
|
// whether it has been successful
|
|
|
|
|
fingerprintSuccess *bool
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-18 09:37:42 +00:00
|
|
|
|
type DockerDriverAuth struct {
|
|
|
|
|
Username string `mapstructure:"username"` // username for the registry
|
|
|
|
|
Password string `mapstructure:"password"` // password to access the registry
|
|
|
|
|
Email string `mapstructure:"email"` // email address of the user who is allowed to access the registry
|
|
|
|
|
ServerAddress string `mapstructure:"server_address"` // server address of the registry
|
2015-11-16 04:25:57 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-09-20 07:41:58 +00:00
|
|
|
|
type DockerLoggingOpts struct {
|
|
|
|
|
Type string `mapstructure:"type"`
|
|
|
|
|
ConfigRaw []map[string]string `mapstructure:"config"`
|
|
|
|
|
Config map[string]string `mapstructure:"-"`
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-23 21:17:00 +00:00
|
|
|
|
type DockerMount struct {
|
2017-09-05 21:02:57 +00:00
|
|
|
|
Target string `mapstructure:"target"`
|
|
|
|
|
Source string `mapstructure:"source"`
|
|
|
|
|
ReadOnly bool `mapstructure:"readonly"`
|
|
|
|
|
VolumeOptions []*DockerVolumeOptions `mapstructure:"volume_options"`
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-11-06 18:27:13 +00:00
|
|
|
|
type DockerDevice struct {
|
|
|
|
|
HostPath string `mapstructure:"host_path"`
|
|
|
|
|
ContainerPath string `mapstructure:"container_path"`
|
|
|
|
|
CgroupPermissions string `mapstructure:"cgroup_permissions"`
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-23 21:17:00 +00:00
|
|
|
|
type DockerVolumeOptions struct {
|
2017-09-05 21:02:57 +00:00
|
|
|
|
NoCopy bool `mapstructure:"no_copy"`
|
|
|
|
|
Labels []map[string]string `mapstructure:"labels"`
|
|
|
|
|
DriverConfig []DockerVolumeDriverConfig `mapstructure:"driver_config"`
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// VolumeDriverConfig holds a map of volume driver specific options
|
2017-08-23 21:17:00 +00:00
|
|
|
|
type DockerVolumeDriverConfig struct {
|
2017-09-05 21:02:57 +00:00
|
|
|
|
Name string `mapstructure:"name"`
|
|
|
|
|
Options []map[string]string `mapstructure:"options"`
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-12-06 21:52:44 +00:00
|
|
|
|
// DockerDriverConfig defines the user specified config block in a jobspec
|
2015-11-14 04:22:49 +00:00
|
|
|
|
type DockerDriverConfig struct {
|
2018-01-31 23:01:25 +00:00
|
|
|
|
ImageName string `mapstructure:"image"` // Container's Image Name
|
|
|
|
|
LoadImage string `mapstructure:"load"` // LoadImage is a path to an image archive file
|
|
|
|
|
Command string `mapstructure:"command"` // The Command to run when the container starts up
|
|
|
|
|
Args []string `mapstructure:"args"` // The arguments to the Command
|
|
|
|
|
Entrypoint []string `mapstructure:"entrypoint"` // Override the containers entrypoint
|
|
|
|
|
IpcMode string `mapstructure:"ipc_mode"` // The IPC mode of the container - host and none
|
|
|
|
|
NetworkMode string `mapstructure:"network_mode"` // The network mode of the container - host, nat and none
|
|
|
|
|
NetworkAliases []string `mapstructure:"network_aliases"` // The network-scoped alias for the container
|
|
|
|
|
IPv4Address string `mapstructure:"ipv4_address"` // The container ipv4 address
|
|
|
|
|
IPv6Address string `mapstructure:"ipv6_address"` // the container ipv6 address
|
|
|
|
|
PidMode string `mapstructure:"pid_mode"` // The PID mode of the container - host and none
|
|
|
|
|
UTSMode string `mapstructure:"uts_mode"` // The UTS mode of the container - host and none
|
|
|
|
|
UsernsMode string `mapstructure:"userns_mode"` // The User namespace mode of the container - host and none
|
|
|
|
|
PortMapRaw []map[string]string `mapstructure:"port_map"` //
|
|
|
|
|
PortMap map[string]int `mapstructure:"-"` // A map of host port labels and the ports exposed on the container
|
|
|
|
|
Privileged bool `mapstructure:"privileged"` // Flag to run the container in privileged mode
|
|
|
|
|
SysctlRaw []map[string]string `mapstructure:"sysctl"` //
|
|
|
|
|
Sysctl map[string]string `mapstructure:"-"` // The sysctl custom configurations
|
|
|
|
|
UlimitRaw []map[string]string `mapstructure:"ulimit"` //
|
|
|
|
|
Ulimit []docker.ULimit `mapstructure:"-"` // The ulimit custom configurations
|
|
|
|
|
DNSServers []string `mapstructure:"dns_servers"` // DNS Server for containers
|
|
|
|
|
DNSSearchDomains []string `mapstructure:"dns_search_domains"` // DNS Search domains for containers
|
|
|
|
|
DNSOptions []string `mapstructure:"dns_options"` // DNS Options
|
|
|
|
|
ExtraHosts []string `mapstructure:"extra_hosts"` // Add host to /etc/hosts (host:IP)
|
|
|
|
|
Hostname string `mapstructure:"hostname"` // Hostname for containers
|
|
|
|
|
LabelsRaw []map[string]string `mapstructure:"labels"` //
|
|
|
|
|
Labels map[string]string `mapstructure:"-"` // Labels to set when the container starts up
|
|
|
|
|
Auth []DockerDriverAuth `mapstructure:"auth"` // Authentication credentials for a private Docker registry
|
|
|
|
|
AuthSoftFail bool `mapstructure:"auth_soft_fail"` // Soft-fail if auth creds are provided but fail
|
|
|
|
|
TTY bool `mapstructure:"tty"` // Allocate a Pseudo-TTY
|
|
|
|
|
Interactive bool `mapstructure:"interactive"` // Keep STDIN open even if not attached
|
|
|
|
|
ShmSize int64 `mapstructure:"shm_size"` // Size of /dev/shm of the container in bytes
|
|
|
|
|
WorkDir string `mapstructure:"work_dir"` // Working directory inside the container
|
|
|
|
|
Logging []DockerLoggingOpts `mapstructure:"logging"` // Logging options for syslog server
|
|
|
|
|
Volumes []string `mapstructure:"volumes"` // Host-Volumes to mount in, syntax: /path/to/host/directory:/destination/path/in/container
|
|
|
|
|
Mounts []DockerMount `mapstructure:"mounts"` // Docker volumes to mount
|
|
|
|
|
VolumeDriver string `mapstructure:"volume_driver"` // Docker volume driver used for the container's volumes
|
|
|
|
|
ForcePull bool `mapstructure:"force_pull"` // Always force pull before running image, useful if your tags are mutable
|
|
|
|
|
MacAddress string `mapstructure:"mac_address"` // Pin mac address to container
|
|
|
|
|
SecurityOpt []string `mapstructure:"security_opt"` // Flags to pass directly to security-opt
|
|
|
|
|
Devices []DockerDevice `mapstructure:"devices"` // To allow mounting USB or other serial control devices
|
|
|
|
|
CapAdd []string `mapstructure:"cap_add"` // Flags to pass directly to cap-add
|
|
|
|
|
CapDrop []string `mapstructure:"cap_drop"` // Flags to pass directly to cap-drop
|
|
|
|
|
ReadonlyRootfs bool `mapstructure:"readonly_rootfs"` // Mount the container’s root filesystem as read only
|
|
|
|
|
AdvertiseIPv6Address bool `mapstructure:"advertise_ipv6_address"` // Flag to use the GlobalIPv6Address from the container as the detected IP
|
2018-02-09 04:14:29 +00:00
|
|
|
|
CPUHardLimit bool `mapstructure:"cpu_hard_limit"` // Enforce CPU hard limit.
|
2015-11-14 02:09:42 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-03-29 14:04:42 +00:00
|
|
|
|
func sliceMergeUlimit(ulimitsRaw map[string]string) ([]docker.ULimit, error) {
|
|
|
|
|
var ulimits []docker.ULimit
|
|
|
|
|
|
|
|
|
|
for name, ulimitRaw := range ulimitsRaw {
|
2017-11-20 18:07:18 +00:00
|
|
|
|
if len(ulimitRaw) == 0 {
|
|
|
|
|
return []docker.ULimit{}, fmt.Errorf("Malformed ulimit specification %v: %q, cannot be empty", name, ulimitRaw)
|
|
|
|
|
}
|
2017-03-29 16:04:37 +00:00
|
|
|
|
// hard limit is optional
|
|
|
|
|
if strings.Contains(ulimitRaw, ":") == false {
|
|
|
|
|
ulimitRaw = ulimitRaw + ":" + ulimitRaw
|
|
|
|
|
}
|
2017-03-29 14:04:42 +00:00
|
|
|
|
|
2017-03-29 16:04:37 +00:00
|
|
|
|
splitted := strings.SplitN(ulimitRaw, ":", 2)
|
2017-11-20 17:15:09 +00:00
|
|
|
|
if len(splitted) < 2 {
|
|
|
|
|
return []docker.ULimit{}, fmt.Errorf("Malformed ulimit specification %v: %v", name, ulimitRaw)
|
|
|
|
|
}
|
2017-03-29 14:04:42 +00:00
|
|
|
|
soft, err := strconv.Atoi(splitted[0])
|
|
|
|
|
if err != nil {
|
2017-11-20 17:15:09 +00:00
|
|
|
|
return []docker.ULimit{}, fmt.Errorf("Malformed soft ulimit %v: %v", name, ulimitRaw)
|
2017-03-29 14:04:42 +00:00
|
|
|
|
}
|
2017-03-29 16:04:37 +00:00
|
|
|
|
hard, err := strconv.Atoi(splitted[1])
|
|
|
|
|
if err != nil {
|
2017-11-20 17:15:09 +00:00
|
|
|
|
return []docker.ULimit{}, fmt.Errorf("Malformed hard ulimit %v: %v", name, ulimitRaw)
|
2017-03-29 16:04:37 +00:00
|
|
|
|
}
|
2017-03-29 14:04:42 +00:00
|
|
|
|
|
|
|
|
|
ulimit := docker.ULimit{
|
|
|
|
|
Name: name,
|
|
|
|
|
Soft: int64(soft),
|
2017-03-29 16:04:37 +00:00
|
|
|
|
Hard: int64(hard),
|
2017-03-29 14:04:42 +00:00
|
|
|
|
}
|
|
|
|
|
ulimits = append(ulimits, ulimit)
|
|
|
|
|
}
|
|
|
|
|
return ulimits, nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-21 23:41:14 +00:00
|
|
|
|
// Validate validates a docker driver config
|
2015-11-14 04:22:49 +00:00
|
|
|
|
func (c *DockerDriverConfig) Validate() error {
|
2015-11-14 02:09:42 +00:00
|
|
|
|
if c.ImageName == "" {
|
|
|
|
|
return fmt.Errorf("Docker Driver needs an image name")
|
|
|
|
|
}
|
2017-11-06 18:27:13 +00:00
|
|
|
|
if len(c.Devices) > 0 {
|
|
|
|
|
for _, dev := range c.Devices {
|
|
|
|
|
if dev.HostPath == "" {
|
|
|
|
|
return fmt.Errorf("host path must be set in configuration for devices")
|
|
|
|
|
}
|
|
|
|
|
if dev.CgroupPermissions != "" {
|
|
|
|
|
for _, c := range dev.CgroupPermissions {
|
|
|
|
|
ch := string(c)
|
|
|
|
|
if ch != "r" && ch != "w" && ch != "m" {
|
|
|
|
|
return fmt.Errorf("invalid cgroup permission string: %q", dev.CgroupPermissions)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-03-31 08:18:26 +00:00
|
|
|
|
c.Sysctl = mapMergeStrStr(c.SysctlRaw...)
|
2017-03-29 14:04:42 +00:00
|
|
|
|
c.Labels = mapMergeStrStr(c.LabelsRaw...)
|
|
|
|
|
if len(c.Logging) > 0 {
|
|
|
|
|
c.Logging[0].Config = mapMergeStrStr(c.Logging[0].ConfigRaw...)
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-31 08:18:26 +00:00
|
|
|
|
mergedUlimitsRaw := mapMergeStrStr(c.UlimitRaw...)
|
|
|
|
|
ulimit, err := sliceMergeUlimit(mergedUlimitsRaw)
|
2017-03-29 14:04:42 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2017-03-31 08:18:26 +00:00
|
|
|
|
c.Ulimit = ulimit
|
2015-11-14 02:09:42 +00:00
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-21 23:41:14 +00:00
|
|
|
|
// NewDockerDriverConfig returns a docker driver config by parsing the HCL
|
|
|
|
|
// config
|
2017-05-19 18:08:49 +00:00
|
|
|
|
func NewDockerDriverConfig(task *structs.Task, env *env.TaskEnv) (*DockerDriverConfig, error) {
|
2016-11-08 22:18:40 +00:00
|
|
|
|
var dconf DockerDriverConfig
|
|
|
|
|
|
|
|
|
|
if err := mapstructure.WeakDecode(task.Config, &dconf); err != nil {
|
2016-06-21 23:41:14 +00:00
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2016-11-08 22:18:40 +00:00
|
|
|
|
|
2017-08-09 12:44:38 +00:00
|
|
|
|
// Interpolate everything that is a string
|
2016-11-08 22:18:40 +00:00
|
|
|
|
dconf.ImageName = env.ReplaceEnv(dconf.ImageName)
|
|
|
|
|
dconf.Command = env.ReplaceEnv(dconf.Command)
|
2018-01-23 22:05:00 +00:00
|
|
|
|
dconf.Entrypoint = env.ParseAndReplace(dconf.Entrypoint)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
dconf.IpcMode = env.ReplaceEnv(dconf.IpcMode)
|
|
|
|
|
dconf.NetworkMode = env.ReplaceEnv(dconf.NetworkMode)
|
2016-11-11 16:38:16 +00:00
|
|
|
|
dconf.NetworkAliases = env.ParseAndReplace(dconf.NetworkAliases)
|
2017-04-07 13:58:17 +00:00
|
|
|
|
dconf.IPv4Address = env.ReplaceEnv(dconf.IPv4Address)
|
|
|
|
|
dconf.IPv6Address = env.ReplaceEnv(dconf.IPv6Address)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
dconf.PidMode = env.ReplaceEnv(dconf.PidMode)
|
|
|
|
|
dconf.UTSMode = env.ReplaceEnv(dconf.UTSMode)
|
|
|
|
|
dconf.Hostname = env.ReplaceEnv(dconf.Hostname)
|
|
|
|
|
dconf.WorkDir = env.ReplaceEnv(dconf.WorkDir)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
dconf.LoadImage = env.ReplaceEnv(dconf.LoadImage)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
dconf.Volumes = env.ParseAndReplace(dconf.Volumes)
|
2017-02-23 17:36:32 +00:00
|
|
|
|
dconf.VolumeDriver = env.ReplaceEnv(dconf.VolumeDriver)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
dconf.DNSServers = env.ParseAndReplace(dconf.DNSServers)
|
|
|
|
|
dconf.DNSSearchDomains = env.ParseAndReplace(dconf.DNSSearchDomains)
|
2017-08-09 11:30:06 +00:00
|
|
|
|
dconf.DNSOptions = env.ParseAndReplace(dconf.DNSOptions)
|
2017-04-11 17:52:24 +00:00
|
|
|
|
dconf.ExtraHosts = env.ParseAndReplace(dconf.ExtraHosts)
|
2017-05-17 14:41:00 +00:00
|
|
|
|
dconf.MacAddress = env.ReplaceEnv(dconf.MacAddress)
|
2017-05-19 23:18:49 +00:00
|
|
|
|
dconf.SecurityOpt = env.ParseAndReplace(dconf.SecurityOpt)
|
2018-01-14 18:56:57 +00:00
|
|
|
|
dconf.CapAdd = env.ParseAndReplace(dconf.CapAdd)
|
|
|
|
|
dconf.CapDrop = env.ParseAndReplace(dconf.CapDrop)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
|
2017-03-31 08:18:26 +00:00
|
|
|
|
for _, m := range dconf.SysctlRaw {
|
2017-03-29 14:04:42 +00:00
|
|
|
|
for k, v := range m {
|
|
|
|
|
delete(m, k)
|
|
|
|
|
m[env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-31 08:18:26 +00:00
|
|
|
|
for _, m := range dconf.UlimitRaw {
|
2017-03-29 14:04:42 +00:00
|
|
|
|
for k, v := range m {
|
|
|
|
|
delete(m, k)
|
|
|
|
|
m[env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-08 22:18:40 +00:00
|
|
|
|
for _, m := range dconf.LabelsRaw {
|
|
|
|
|
for k, v := range m {
|
|
|
|
|
delete(m, k)
|
|
|
|
|
m[env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
|
|
|
|
}
|
2016-06-21 23:41:14 +00:00
|
|
|
|
}
|
2017-06-08 20:12:32 +00:00
|
|
|
|
dconf.Labels = mapMergeStrStr(dconf.LabelsRaw...)
|
2016-06-21 23:41:14 +00:00
|
|
|
|
|
2016-12-06 20:30:23 +00:00
|
|
|
|
for i, a := range dconf.Auth {
|
|
|
|
|
dconf.Auth[i].Username = env.ReplaceEnv(a.Username)
|
|
|
|
|
dconf.Auth[i].Password = env.ReplaceEnv(a.Password)
|
|
|
|
|
dconf.Auth[i].Email = env.ReplaceEnv(a.Email)
|
|
|
|
|
dconf.Auth[i].ServerAddress = env.ReplaceEnv(a.ServerAddress)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-19 21:42:58 +00:00
|
|
|
|
for i, l := range dconf.Logging {
|
|
|
|
|
dconf.Logging[i].Type = env.ReplaceEnv(l.Type)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
for _, c := range l.ConfigRaw {
|
|
|
|
|
for k, v := range c {
|
|
|
|
|
delete(c, k)
|
|
|
|
|
c[env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-10 16:31:53 +00:00
|
|
|
|
for i, m := range dconf.Mounts {
|
|
|
|
|
dconf.Mounts[i].Target = env.ReplaceEnv(m.Target)
|
|
|
|
|
dconf.Mounts[i].Source = env.ReplaceEnv(m.Source)
|
2017-09-05 21:02:57 +00:00
|
|
|
|
|
|
|
|
|
if len(m.VolumeOptions) > 1 {
|
|
|
|
|
return nil, fmt.Errorf("Only one volume_options stanza allowed")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(m.VolumeOptions) == 1 {
|
|
|
|
|
vo := m.VolumeOptions[0]
|
|
|
|
|
if len(vo.Labels) > 1 {
|
|
|
|
|
return nil, fmt.Errorf("labels may only be specified once in volume_options stanza")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(vo.Labels) == 1 {
|
|
|
|
|
for k, v := range vo.Labels[0] {
|
2017-08-10 16:31:53 +00:00
|
|
|
|
if k != env.ReplaceEnv(k) {
|
2017-09-05 21:02:57 +00:00
|
|
|
|
delete(vo.Labels[0], k)
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
2017-09-05 21:02:57 +00:00
|
|
|
|
vo.Labels[0][env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-05 21:02:57 +00:00
|
|
|
|
|
|
|
|
|
if len(vo.DriverConfig) > 1 {
|
|
|
|
|
return nil, fmt.Errorf("volume driver config may only be specified once")
|
|
|
|
|
}
|
|
|
|
|
if len(vo.DriverConfig) == 1 {
|
|
|
|
|
vo.DriverConfig[0].Name = env.ReplaceEnv(vo.DriverConfig[0].Name)
|
|
|
|
|
if len(vo.DriverConfig[0].Options) > 1 {
|
|
|
|
|
return nil, fmt.Errorf("volume driver options may only be specified once")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(vo.DriverConfig[0].Options) == 1 {
|
|
|
|
|
options := vo.DriverConfig[0].Options[0]
|
|
|
|
|
for k, v := range options {
|
|
|
|
|
if k != env.ReplaceEnv(k) {
|
|
|
|
|
delete(options, k)
|
|
|
|
|
}
|
|
|
|
|
options[env.ReplaceEnv(k)] = env.ReplaceEnv(v)
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-08 20:12:32 +00:00
|
|
|
|
if len(dconf.Logging) > 0 {
|
|
|
|
|
dconf.Logging[0].Config = mapMergeStrStr(dconf.Logging[0].ConfigRaw...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
portMap := make(map[string]int)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
for _, m := range dconf.PortMapRaw {
|
|
|
|
|
for k, v := range m {
|
2017-06-08 20:12:32 +00:00
|
|
|
|
ki, vi := env.ReplaceEnv(k), env.ReplaceEnv(v)
|
|
|
|
|
p, err := strconv.Atoi(vi)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to parse port map value %v to %v: %v", ki, vi, err)
|
|
|
|
|
}
|
|
|
|
|
portMap[ki] = p
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-06-08 20:12:32 +00:00
|
|
|
|
dconf.PortMap = portMap
|
2016-11-08 22:18:40 +00:00
|
|
|
|
|
|
|
|
|
// Remove any http
|
|
|
|
|
if strings.Contains(dconf.ImageName, "https://") {
|
|
|
|
|
dconf.ImageName = strings.Replace(dconf.ImageName, "https://", "", 1)
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-09 00:50:09 +00:00
|
|
|
|
// If devices are configured set default cgroup permissions
|
|
|
|
|
if len(dconf.Devices) > 0 {
|
|
|
|
|
for i, dev := range dconf.Devices {
|
|
|
|
|
if dev.CgroupPermissions == "" {
|
|
|
|
|
dev.CgroupPermissions = "rwm"
|
|
|
|
|
}
|
|
|
|
|
dconf.Devices[i] = dev
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err := dconf.Validate(); err != nil {
|
2016-06-21 23:41:14 +00:00
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2016-11-08 22:18:40 +00:00
|
|
|
|
return &dconf, nil
|
2016-06-21 23:41:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
type dockerPID struct {
|
2016-03-03 17:21:21 +00:00
|
|
|
|
Version string
|
2017-02-24 21:20:40 +00:00
|
|
|
|
Image string
|
2016-03-03 17:21:21 +00:00
|
|
|
|
ImageID string
|
|
|
|
|
ContainerID string
|
|
|
|
|
KillTimeout time.Duration
|
|
|
|
|
MaxKillTimeout time.Duration
|
|
|
|
|
PluginConfig *PluginReattachConfig
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-19 22:20:41 +00:00
|
|
|
|
type DockerHandle struct {
|
2016-05-25 19:36:37 +00:00
|
|
|
|
pluginClient *plugin.Client
|
|
|
|
|
executor executor.Executor
|
|
|
|
|
client *docker.Client
|
2016-06-11 18:34:41 +00:00
|
|
|
|
waitClient *docker.Client
|
2016-05-25 19:36:37 +00:00
|
|
|
|
logger *log.Logger
|
2017-02-24 21:20:40 +00:00
|
|
|
|
Image string
|
|
|
|
|
ImageID string
|
2016-05-25 19:36:37 +00:00
|
|
|
|
containerID string
|
|
|
|
|
version string
|
|
|
|
|
killTimeout time.Duration
|
|
|
|
|
maxKillTimeout time.Duration
|
|
|
|
|
resourceUsageLock sync.RWMutex
|
|
|
|
|
resourceUsage *cstructs.TaskResourceUsage
|
2016-06-12 03:15:50 +00:00
|
|
|
|
waitCh chan *dstructs.WaitResult
|
2016-05-26 18:52:01 +00:00
|
|
|
|
doneCh chan bool
|
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
|
|
|
|
}
|
|
|
|
|
|
2018-01-24 14:09:53 +00:00
|
|
|
|
func (d *DockerDriver) Fingerprint(req *cstructs.FingerprintRequest, resp *cstructs.FingerprintResponse) error {
|
2017-02-21 03:35:51 +00:00
|
|
|
|
client, _, err := d.dockerClients()
|
|
|
|
|
if err != nil {
|
|
|
|
|
if d.fingerprintSuccess == nil || *d.fingerprintSuccess {
|
|
|
|
|
d.logger.Printf("[INFO] driver.docker: failed to initialize client: %s", err)
|
|
|
|
|
}
|
|
|
|
|
d.fingerprintSuccess = helper.BoolToPtr(false)
|
2018-01-24 14:09:53 +00:00
|
|
|
|
return nil
|
2017-02-21 03:35:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// This is the first operation taken on the client so we'll try to
|
|
|
|
|
// establish a connection to the Docker daemon. If this fails it means
|
|
|
|
|
// Docker isn't available so we'll simply disable the docker driver.
|
|
|
|
|
env, err := client.Version()
|
|
|
|
|
if err != nil {
|
|
|
|
|
if d.fingerprintSuccess == nil || *d.fingerprintSuccess {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: could not connect to docker daemon at %s: %s", client.Endpoint(), err)
|
|
|
|
|
}
|
|
|
|
|
d.fingerprintSuccess = helper.BoolToPtr(false)
|
2018-01-26 19:31:37 +00:00
|
|
|
|
resp.RemoveAttribute(dockerDriverAttr)
|
2018-01-24 14:09:53 +00:00
|
|
|
|
return nil
|
2017-02-21 03:35:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-01-26 16:21:07 +00:00
|
|
|
|
resp.AddAttribute(dockerDriverAttr, "1")
|
|
|
|
|
resp.AddAttribute("driver.docker.version", env.Get("Version"))
|
2018-01-31 22:03:55 +00:00
|
|
|
|
resp.Detected = true
|
2017-02-21 03:35:51 +00:00
|
|
|
|
|
|
|
|
|
privileged := d.config.ReadBoolDefault(dockerPrivilegedConfigOption, false)
|
|
|
|
|
if privileged {
|
2018-01-26 16:21:07 +00:00
|
|
|
|
resp.AddAttribute(dockerPrivilegedConfigOption, "1")
|
2017-02-21 03:35:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Advertise if this node supports Docker volumes
|
|
|
|
|
if d.config.ReadBoolDefault(dockerVolumesConfigOption, dockerVolumesConfigDefault) {
|
2018-01-26 16:21:07 +00:00
|
|
|
|
resp.AddAttribute("driver."+dockerVolumesConfigOption, "1")
|
2017-02-21 03:35:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-07-07 17:14:10 +00:00
|
|
|
|
// Detect bridge IP address - #2785
|
|
|
|
|
if nets, err := client.ListNetworks(); err != nil {
|
|
|
|
|
d.logger.Printf("[WARN] driver.docker: error discovering bridge IP: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
for _, n := range nets {
|
|
|
|
|
if n.Name != "bridge" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(n.IPAM.Config) == 0 {
|
|
|
|
|
d.logger.Printf("[WARN] driver.docker: no IPAM config for bridge network")
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-18 17:34:45 +00:00
|
|
|
|
if n.IPAM.Config[0].Gateway != "" {
|
2018-01-26 16:21:07 +00:00
|
|
|
|
resp.AddAttribute("driver.docker.bridge_ip", n.IPAM.Config[0].Gateway)
|
2017-10-18 17:34:45 +00:00
|
|
|
|
} else if d.fingerprintSuccess == nil {
|
|
|
|
|
// Docker 17.09.0-ce dropped the Gateway IP from the bridge network
|
|
|
|
|
// See https://github.com/moby/moby/issues/32648
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: bridge_ip could not be discovered")
|
|
|
|
|
}
|
|
|
|
|
break
|
2017-07-07 17:14:10 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 03:35:51 +00:00
|
|
|
|
d.fingerprintSuccess = helper.BoolToPtr(true)
|
2018-01-24 14:09:53 +00:00
|
|
|
|
return nil
|
2017-02-21 03:35:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-06 21:03:24 +00:00
|
|
|
|
// HealthCheck implements the interface for the HealthCheck interface. This
|
2018-01-25 16:30:15 +00:00
|
|
|
|
// performs a health check on the docker driver, asserting whether the docker
|
|
|
|
|
// driver is responsive to a `docker ps` command.
|
|
|
|
|
func (d *DockerDriver) HealthCheck(req *cstructs.HealthCheckRequest, resp *cstructs.HealthCheckResponse) error {
|
2018-03-20 22:05:43 +00:00
|
|
|
|
dinfo := &structs.DriverInfo{
|
|
|
|
|
UpdateTime: time.Now(),
|
2018-01-25 16:30:15 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-03 20:55:46 +00:00
|
|
|
|
healthCheckClient, err := d.dockerHealthCheckClient()
|
2018-02-27 19:57:10 +00:00
|
|
|
|
if err != nil {
|
2018-03-06 21:03:24 +00:00
|
|
|
|
d.logger.Printf("[WARN] driver.docker: failed to retrieve Docker client in the process of a docker health check: %v", err)
|
2018-03-20 22:05:43 +00:00
|
|
|
|
dinfo.HealthDescription = fmt.Sprintf("Failed retrieving Docker client: %v", err)
|
|
|
|
|
resp.AddDriverInfo("docker", dinfo)
|
|
|
|
|
return nil
|
2018-02-27 19:57:10 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-03 20:55:46 +00:00
|
|
|
|
_, err = healthCheckClient.ListContainers(docker.ListContainersOptions{All: false})
|
2018-01-25 16:30:15 +00:00
|
|
|
|
if err != nil {
|
2018-03-19 12:06:09 +00:00
|
|
|
|
d.logger.Printf("[WARN] driver.docker: failed to list Docker containers in the process of a Docker health check: %v", err)
|
2018-03-20 22:05:43 +00:00
|
|
|
|
dinfo.HealthDescription = fmt.Sprintf("Failed to list Docker containers: %v", err)
|
|
|
|
|
resp.AddDriverInfo("docker", dinfo)
|
|
|
|
|
return nil
|
2018-01-25 16:30:15 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
d.logger.Printf("[TRACE] driver.docker: docker driver is available and is responsive to `docker ps`")
|
2018-03-20 22:05:43 +00:00
|
|
|
|
dinfo.Healthy = true
|
2018-03-23 00:18:32 +00:00
|
|
|
|
dinfo.HealthDescription = "Driver is available and responsive"
|
2018-03-20 22:05:43 +00:00
|
|
|
|
resp.AddDriverInfo("docker", dinfo)
|
2018-01-25 16:30:15 +00:00
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetHealthChecks implements the interface for the HealthCheck interface. This
|
|
|
|
|
// sets whether the driver is eligible for periodic health checks and the
|
|
|
|
|
// interval at which to do them.
|
|
|
|
|
func (d *DockerDriver) GetHealthCheckInterval(req *cstructs.HealthCheckIntervalRequest, resp *cstructs.HealthCheckIntervalResponse) error {
|
|
|
|
|
resp.Eligible = true
|
2018-02-28 19:32:54 +00:00
|
|
|
|
resp.Period = 1 * time.Minute
|
2018-01-25 16:30:15 +00:00
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-09 22:38:42 +00:00
|
|
|
|
// Validate is used to validate the driver configuration
|
2016-04-08 20:19:43 +00:00
|
|
|
|
func (d *DockerDriver) Validate(config map[string]interface{}) error {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
fd := &fields.FieldData{
|
2016-04-08 20:19:43 +00:00
|
|
|
|
Raw: config,
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Schema: map[string]*fields.FieldSchema{
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"image": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
Required: true,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"load": {
|
2017-02-24 21:20:40 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"command": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"args": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2018-01-23 22:05:00 +00:00
|
|
|
|
"entrypoint": {
|
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"ipc_mode": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"network_mode": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"network_aliases": {
|
2016-11-11 16:38:16 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"ipv4_address": {
|
2017-04-07 13:58:17 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"ipv6_address": {
|
2017-04-07 13:58:17 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"mac_address": {
|
2017-05-17 14:41:00 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"pid_mode": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"uts_mode": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"userns_mode": {
|
2016-11-04 23:53:56 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-11-18 15:23:09 +00:00
|
|
|
|
"sysctl": {
|
2017-03-29 14:04:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-11-18 15:23:09 +00:00
|
|
|
|
"ulimit": {
|
2017-03-29 14:04:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"port_map": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"privileged": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"dns_servers": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"dns_options": {
|
2017-08-09 11:30:06 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"dns_search_domains": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"extra_hosts": {
|
2017-04-11 17:52:24 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"hostname": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"labels": {
|
2016-04-25 21:58:31 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"auth": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"auth_soft_fail": {
|
2017-07-06 18:35:34 +00:00
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2017-01-12 22:07:36 +00:00
|
|
|
|
// COMPAT: Remove in 0.6.0. SSL is no longer needed
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"ssl": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"tty": {
|
2016-04-09 22:38:42 +00:00
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"interactive": {
|
2016-04-10 10:20:01 +00:00
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"shm_size": {
|
2016-05-27 10:30:04 +00:00
|
|
|
|
Type: fields.TypeInt,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"work_dir": {
|
2016-08-03 14:18:15 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"logging": {
|
2016-09-20 07:41:58 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"volumes": {
|
2016-09-20 09:22:27 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"volume_driver": {
|
2017-02-23 17:36:32 +00:00
|
|
|
|
Type: fields.TypeString,
|
|
|
|
|
},
|
2017-08-10 16:31:53 +00:00
|
|
|
|
"mounts": {
|
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"force_pull": {
|
2016-12-28 18:18:38 +00:00
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"security_opt": {
|
2017-05-19 23:18:49 +00:00
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2017-11-06 18:27:13 +00:00
|
|
|
|
"devices": {
|
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2018-01-14 18:56:57 +00:00
|
|
|
|
"cap_add": {
|
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
|
|
|
|
"cap_drop": {
|
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
|
},
|
2018-01-27 13:38:29 +00:00
|
|
|
|
"readonly_rootfs": {
|
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2018-01-31 23:01:25 +00:00
|
|
|
|
"advertise_ipv6_address": {
|
2018-01-24 13:39:50 +00:00
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2018-02-01 18:09:12 +00:00
|
|
|
|
"cpu_hard_limit": {
|
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
|
},
|
2016-04-08 20:19:43 +00:00
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := fd.Validate(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-19 22:06:23 +00:00
|
|
|
|
func (d *DockerDriver) Abilities() DriverAbilities {
|
|
|
|
|
return DriverAbilities{
|
|
|
|
|
SendSignals: true,
|
2017-04-13 16:52:16 +00:00
|
|
|
|
Exec: true,
|
2016-10-19 22:06:23 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
|
func (d *DockerDriver) FSIsolation() cstructs.FSIsolation {
|
|
|
|
|
return cstructs.FSIsolationImage
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
// getDockerCoordinator returns the docker coordinator and the caller ID to use when
|
|
|
|
|
// interacting with the coordinator
|
|
|
|
|
func (d *DockerDriver) getDockerCoordinator(client *docker.Client) (*dockerCoordinator, string) {
|
2017-02-24 21:20:40 +00:00
|
|
|
|
config := &dockerCoordinatorConfig{
|
|
|
|
|
client: client,
|
|
|
|
|
cleanup: d.config.ReadBoolDefault(dockerCleanupImageConfigOption, dockerCleanupImageConfigDefault),
|
|
|
|
|
logger: d.logger,
|
|
|
|
|
removeDelay: d.config.ReadDurationDefault(dockerImageRemoveDelayConfigOption, dockerImageRemoveDelayConfigDefault),
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
return GetDockerCoordinator(config), fmt.Sprintf("%s-%s", d.DriverContext.allocID, d.DriverContext.taskName)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-19 18:08:49 +00:00
|
|
|
|
func (d *DockerDriver) Prestart(ctx *ExecContext, task *structs.Task) (*PrestartResponse, error) {
|
2017-05-23 00:46:40 +00:00
|
|
|
|
driverConfig, err := NewDockerDriverConfig(task, ctx.TaskEnv)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err != nil {
|
2017-01-10 21:24:45 +00:00
|
|
|
|
return nil, err
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
// Set state needed by Start
|
2017-01-10 21:24:45 +00:00
|
|
|
|
d.driverConfig = driverConfig
|
|
|
|
|
|
2016-11-08 22:18:40 +00:00
|
|
|
|
// Initialize docker API clients
|
2016-12-20 22:29:57 +00:00
|
|
|
|
client, _, err := d.dockerClients()
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err != nil {
|
2017-01-10 21:24:45 +00:00
|
|
|
|
return nil, fmt.Errorf("Failed to connect to docker daemon: %s", err)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
|
// Ensure the image is available
|
2017-02-24 21:20:40 +00:00
|
|
|
|
id, err := d.createImage(driverConfig, client, ctx.TaskDir)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err != nil {
|
2017-01-18 00:04:09 +00:00
|
|
|
|
return nil, err
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
2017-02-24 21:20:40 +00:00
|
|
|
|
d.imageID = id
|
2016-11-08 22:18:40 +00:00
|
|
|
|
|
2017-05-19 18:08:49 +00:00
|
|
|
|
resp := NewPrestartResponse()
|
|
|
|
|
resp.CreatedResources.Add(dockerImageResKey, id)
|
2017-06-13 21:02:11 +00:00
|
|
|
|
|
|
|
|
|
// Return the PortMap if it's set
|
|
|
|
|
if len(driverConfig.PortMap) > 0 {
|
|
|
|
|
resp.Network = &cstructs.DriverNetwork{
|
|
|
|
|
PortMap: driverConfig.PortMap,
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-05-19 18:08:49 +00:00
|
|
|
|
return resp, nil
|
2016-11-30 00:39:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
func (d *DockerDriver) Start(ctx *ExecContext, task *structs.Task) (*StartResponse, error) {
|
2017-01-06 00:02:20 +00:00
|
|
|
|
pluginLogFile := filepath.Join(ctx.TaskDir.Dir, "executor.out")
|
2017-01-12 19:50:49 +00:00
|
|
|
|
executorConfig := &dstructs.ExecutorConfig{
|
|
|
|
|
LogFile: pluginLogFile,
|
|
|
|
|
LogLevel: d.config.LogLevel,
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-12 19:50:49 +00:00
|
|
|
|
exec, pluginClient, err := createExecutor(d.config.LogOutput, d.config, executorConfig)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
executorCtx := &executor.ExecutorContext{
|
2017-05-23 00:46:40 +00:00
|
|
|
|
TaskEnv: ctx.TaskEnv,
|
2016-11-08 22:18:40 +00:00
|
|
|
|
Task: task,
|
|
|
|
|
Driver: "docker",
|
2016-12-03 01:04:07 +00:00
|
|
|
|
LogDir: ctx.TaskDir.LogDir,
|
|
|
|
|
TaskDir: ctx.TaskDir.Dir,
|
2016-11-08 22:18:40 +00:00
|
|
|
|
PortLowerBound: d.config.ClientMinPort,
|
|
|
|
|
PortUpperBound: d.config.ClientMaxPort,
|
|
|
|
|
}
|
|
|
|
|
if err := exec.SetContext(executorCtx); err != nil {
|
|
|
|
|
pluginClient.Kill()
|
|
|
|
|
return nil, fmt.Errorf("failed to set executor context: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-10 21:57:48 +00:00
|
|
|
|
// The user hasn't specified any logging options so launch our own syslog
|
|
|
|
|
// server if possible.
|
2016-11-08 22:18:40 +00:00
|
|
|
|
syslogAddr := ""
|
2017-09-10 21:57:48 +00:00
|
|
|
|
if len(d.driverConfig.Logging) == 0 {
|
|
|
|
|
if runtime.GOOS == "darwin" {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: disabling syslog driver as Docker for Mac workaround")
|
|
|
|
|
} else {
|
|
|
|
|
ss, err := exec.LaunchSyslogServer()
|
|
|
|
|
if err != nil {
|
|
|
|
|
pluginClient.Kill()
|
|
|
|
|
return nil, fmt.Errorf("failed to start syslog collector: %v", err)
|
|
|
|
|
}
|
|
|
|
|
syslogAddr = ss.Addr
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-30 00:39:36 +00:00
|
|
|
|
config, err := d.createContainerConfig(ctx, task, d.driverConfig, syslogAddr)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
if err != nil {
|
2017-01-14 00:53:58 +00:00
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed to create container configuration for image %q (%q): %v", d.driverConfig.ImageName, d.imageID, err)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
pluginClient.Kill()
|
2017-01-14 00:53:58 +00:00
|
|
|
|
return nil, fmt.Errorf("Failed to create container configuration for image %q (%q): %v", d.driverConfig.ImageName, d.imageID, err)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-16 00:52:43 +00:00
|
|
|
|
container, err := d.createContainer(client, config)
|
2017-01-14 00:46:08 +00:00
|
|
|
|
if err != nil {
|
2017-03-27 22:37:15 +00:00
|
|
|
|
wrapped := fmt.Sprintf("Failed to create container: %v", err)
|
|
|
|
|
d.logger.Printf("[ERR] driver.docker: %s", wrapped)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
pluginClient.Kill()
|
2017-03-27 22:37:15 +00:00
|
|
|
|
return nil, structs.WrapRecoverable(wrapped, err)
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
d.logger.Printf("[INFO] driver.docker: created container %s", container.ID)
|
|
|
|
|
|
2016-11-30 00:29:30 +00:00
|
|
|
|
// We don't need to start the container if the container is already running
|
|
|
|
|
// since we don't create containers which are already present on the host
|
|
|
|
|
// and are running
|
|
|
|
|
if !container.State.Running {
|
|
|
|
|
// Start the container
|
2016-12-20 19:55:40 +00:00
|
|
|
|
if err := d.startContainer(container); err != nil {
|
2016-11-30 00:29:30 +00:00
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed to start container %s: %s", container.ID, err)
|
|
|
|
|
pluginClient.Kill()
|
2017-08-22 13:03:31 +00:00
|
|
|
|
return nil, structs.NewRecoverableError(fmt.Errorf("Failed to start container %s: %s", container.ID, err), structs.IsRecoverable(err))
|
2016-11-30 00:29:30 +00:00
|
|
|
|
}
|
2017-07-14 17:48:19 +00:00
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
// InspectContainer to get all of the container metadata as
|
|
|
|
|
// much of the metadata (eg networking) isn't populated until
|
|
|
|
|
// the container is started
|
2017-07-14 17:48:19 +00:00
|
|
|
|
runningContainer, err := client.InspectContainer(container.ID)
|
|
|
|
|
if err != nil {
|
2017-06-09 17:29:41 +00:00
|
|
|
|
err = fmt.Errorf("failed to inspect started container %s: %s", container.ID, err)
|
|
|
|
|
d.logger.Printf("[ERR] driver.docker: %v", err)
|
|
|
|
|
pluginClient.Kill()
|
|
|
|
|
return nil, structs.NewRecoverableError(err, true)
|
|
|
|
|
}
|
2017-07-14 17:48:19 +00:00
|
|
|
|
container = runningContainer
|
2016-11-30 00:29:30 +00:00
|
|
|
|
d.logger.Printf("[INFO] driver.docker: started container %s", container.ID)
|
|
|
|
|
} else {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: re-attaching to container %s with status %q",
|
|
|
|
|
container.ID, container.State.String())
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Return a driver handle
|
|
|
|
|
maxKill := d.DriverContext.config.MaxKillTimeout
|
|
|
|
|
h := &DockerHandle{
|
|
|
|
|
client: client,
|
|
|
|
|
waitClient: waitClient,
|
|
|
|
|
executor: exec,
|
|
|
|
|
pluginClient: pluginClient,
|
|
|
|
|
logger: d.logger,
|
2017-02-24 21:20:40 +00:00
|
|
|
|
Image: d.driverConfig.ImageName,
|
|
|
|
|
ImageID: d.imageID,
|
2016-11-08 22:18:40 +00:00
|
|
|
|
containerID: container.ID,
|
2017-08-16 22:42:15 +00:00
|
|
|
|
version: d.config.Version.VersionNumber(),
|
2016-11-08 22:18:40 +00:00
|
|
|
|
killTimeout: GetKillTimeout(task.KillTimeout, maxKill),
|
|
|
|
|
maxKillTimeout: maxKill,
|
|
|
|
|
doneCh: make(chan bool),
|
|
|
|
|
waitCh: make(chan *dstructs.WaitResult, 1),
|
|
|
|
|
}
|
|
|
|
|
go h.collectStats()
|
|
|
|
|
go h.run()
|
2017-06-09 17:29:41 +00:00
|
|
|
|
|
|
|
|
|
// Detect container address
|
|
|
|
|
ip, autoUse := d.detectIP(container)
|
|
|
|
|
|
|
|
|
|
// Create a response with the driver handle and container network metadata
|
|
|
|
|
resp := &StartResponse{
|
|
|
|
|
Handle: h,
|
|
|
|
|
Network: &cstructs.DriverNetwork{
|
2017-06-13 21:02:11 +00:00
|
|
|
|
PortMap: d.driverConfig.PortMap,
|
|
|
|
|
IP: ip,
|
|
|
|
|
AutoAdvertise: autoUse,
|
2017-06-09 17:29:41 +00:00
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
return resp, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-23 22:20:04 +00:00
|
|
|
|
// detectIP of Docker container. Returns the first IP found as well as true if
|
|
|
|
|
// the IP should be advertised (bridge network IPs return false). Returns an
|
|
|
|
|
// empty string and false if no IP could be found.
|
2017-06-09 17:29:41 +00:00
|
|
|
|
func (d *DockerDriver) detectIP(c *docker.Container) (string, bool) {
|
|
|
|
|
if c.NetworkSettings == nil {
|
|
|
|
|
// This should only happen if there's been a coding error (such
|
2018-03-11 18:15:27 +00:00
|
|
|
|
// as not calling InspectContainer after CreateContainer). Code
|
2017-06-09 17:29:41 +00:00
|
|
|
|
// defensively in case the Docker API changes subtly.
|
2017-06-21 21:23:58 +00:00
|
|
|
|
d.logger.Printf("[ERROR] driver.docker: no network settings for container %s", c.ID)
|
2017-06-09 17:29:41 +00:00
|
|
|
|
return "", false
|
|
|
|
|
}
|
2017-06-23 22:20:04 +00:00
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
ip, ipName := "", ""
|
|
|
|
|
auto := false
|
|
|
|
|
for name, net := range c.NetworkSettings.Networks {
|
|
|
|
|
if net.IPAddress == "" {
|
|
|
|
|
// Ignore networks without an IP address
|
|
|
|
|
continue
|
|
|
|
|
}
|
2017-06-23 22:20:04 +00:00
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
ip = net.IPAddress
|
2018-01-31 23:01:25 +00:00
|
|
|
|
if d.driverConfig.AdvertiseIPv6Address {
|
2018-01-24 13:39:50 +00:00
|
|
|
|
ip = net.GlobalIPv6Address
|
2018-01-31 23:01:25 +00:00
|
|
|
|
auto = true
|
2018-01-24 13:39:50 +00:00
|
|
|
|
}
|
2017-06-09 17:29:41 +00:00
|
|
|
|
ipName = name
|
|
|
|
|
|
2017-09-27 23:49:23 +00:00
|
|
|
|
// Don't auto-advertise IPs for default networks (bridge on
|
|
|
|
|
// Linux, nat on Windows)
|
|
|
|
|
if name != "bridge" && name != "nat" {
|
2017-06-09 17:29:41 +00:00
|
|
|
|
auto = true
|
|
|
|
|
}
|
2017-06-23 22:20:04 +00:00
|
|
|
|
|
2017-06-21 21:39:35 +00:00
|
|
|
|
break
|
2017-06-09 17:29:41 +00:00
|
|
|
|
}
|
2017-06-23 22:20:04 +00:00
|
|
|
|
|
2017-06-21 21:39:35 +00:00
|
|
|
|
if n := len(c.NetworkSettings.Networks); n > 1 {
|
2017-12-20 23:02:34 +00:00
|
|
|
|
d.logger.Printf("[WARN] driver.docker: task %s multiple (%d) Docker networks for container %q but Nomad only supports 1: choosing %q", d.taskName, n, c.ID, ipName)
|
2017-06-09 17:29:41 +00:00
|
|
|
|
}
|
2017-06-23 22:20:04 +00:00
|
|
|
|
|
2017-06-09 17:29:41 +00:00
|
|
|
|
return ip, auto
|
2016-11-08 22:18:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-14 00:46:08 +00:00
|
|
|
|
func (d *DockerDriver) Cleanup(_ *ExecContext, res *CreatedResources) error {
|
|
|
|
|
retry := false
|
|
|
|
|
var merr multierror.Error
|
|
|
|
|
for key, resources := range res.Resources {
|
|
|
|
|
switch key {
|
|
|
|
|
case dockerImageResKey:
|
|
|
|
|
for _, value := range resources {
|
2017-01-18 00:41:59 +00:00
|
|
|
|
err := d.cleanupImage(value)
|
|
|
|
|
if err != nil {
|
2017-01-14 00:46:08 +00:00
|
|
|
|
if structs.IsRecoverable(err) {
|
|
|
|
|
retry = true
|
|
|
|
|
}
|
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
2017-01-18 00:41:59 +00:00
|
|
|
|
continue
|
2017-01-14 00:46:08 +00:00
|
|
|
|
}
|
2017-01-18 00:41:59 +00:00
|
|
|
|
|
|
|
|
|
// Remove cleaned image from resources
|
|
|
|
|
res.Remove(dockerImageResKey, value)
|
2017-01-14 00:46:08 +00:00
|
|
|
|
}
|
|
|
|
|
default:
|
2017-01-19 17:48:07 +00:00
|
|
|
|
d.logger.Printf("[ERR] driver.docker: unknown resource to cleanup: %q", key)
|
2017-01-14 00:46:08 +00:00
|
|
|
|
}
|
2017-01-10 21:24:45 +00:00
|
|
|
|
}
|
2017-01-14 00:46:08 +00:00
|
|
|
|
return structs.NewRecoverableError(merr.ErrorOrNil(), retry)
|
2017-01-13 01:21:54 +00:00
|
|
|
|
}
|
2017-01-10 21:24:45 +00:00
|
|
|
|
|
2017-01-13 01:21:54 +00:00
|
|
|
|
// cleanupImage removes a Docker image. No error is returned if the image
|
|
|
|
|
// doesn't exist or is still in use. Requires the global client to already be
|
|
|
|
|
// initialized.
|
2017-03-26 00:05:53 +00:00
|
|
|
|
func (d *DockerDriver) cleanupImage(imageID string) error {
|
2017-01-13 01:21:54 +00:00
|
|
|
|
if !d.config.ReadBoolDefault(dockerCleanupImageConfigOption, dockerCleanupImageConfigDefault) {
|
|
|
|
|
// Config says not to cleanup
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator, callerID := d.getDockerCoordinator(client)
|
|
|
|
|
coordinator.RemoveImage(imageID, callerID)
|
2017-01-13 01:21:54 +00:00
|
|
|
|
|
|
|
|
|
return nil
|
2017-01-10 21:24:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-05 16:21:29 +00:00
|
|
|
|
// dockerHealthCheckClient creates a single *docker.Client with a timeout of
|
|
|
|
|
// one minute, which will be used when performing Docker health checks.
|
2018-04-03 20:55:46 +00:00
|
|
|
|
func (d *DockerDriver) dockerHealthCheckClient() (*docker.Client, error) {
|
2018-04-05 16:21:29 +00:00
|
|
|
|
createClientsLock.Lock()
|
|
|
|
|
defer createClientsLock.Unlock()
|
|
|
|
|
|
2018-04-03 20:55:46 +00:00
|
|
|
|
if healthCheckClient != nil {
|
|
|
|
|
return healthCheckClient, nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-09 14:34:17 +00:00
|
|
|
|
var err error
|
|
|
|
|
healthCheckClient, err = d.newDockerClient(dockerHealthCheckTimeout)
|
2018-04-03 20:55:46 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return healthCheckClient, nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-05 16:21:29 +00:00
|
|
|
|
// dockerClients creates two *docker.Client, one for long running operations and
|
|
|
|
|
// the other for shorter operations. 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.
|
|
|
|
|
func (d *DockerDriver) dockerClients() (*docker.Client, *docker.Client, error) {
|
|
|
|
|
createClientsLock.Lock()
|
|
|
|
|
defer createClientsLock.Unlock()
|
|
|
|
|
|
|
|
|
|
if client != nil && waitClient != nil {
|
|
|
|
|
return client, waitClient, nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-09 14:34:17 +00:00
|
|
|
|
var err error
|
2018-04-09 18:13:07 +00:00
|
|
|
|
|
|
|
|
|
// Onlt initialize the client if it hasn't yet been done
|
|
|
|
|
if client == nil {
|
|
|
|
|
client, err = d.newDockerClient(dockerTimeout)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
2018-04-05 16:21:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-09 18:13:07 +00:00
|
|
|
|
// Only initialize the waitClient if it hasn't yet been done
|
|
|
|
|
if waitClient == nil {
|
|
|
|
|
waitClient, err = d.newDockerClient(0 * time.Minute)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
2018-04-05 16:21:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-09 14:34:17 +00:00
|
|
|
|
return client, waitClient, nil
|
2018-04-05 16:21:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// newDockerClient creates a new *docker.Client with a configurable timeout
|
2018-04-03 20:34:50 +00:00
|
|
|
|
func (d *DockerDriver) newDockerClient(timeout time.Duration) (*docker.Client, error) {
|
2015-12-10 21:49:29 +00:00
|
|
|
|
var err error
|
2016-06-11 18:34:41 +00:00
|
|
|
|
var merr multierror.Error
|
2018-04-03 20:34:50 +00:00
|
|
|
|
var newClient *docker.Client
|
|
|
|
|
|
2018-04-05 15:47:56 +00:00
|
|
|
|
// Default to using whatever is configured in docker.endpoint. If this is
|
|
|
|
|
// not specified we'll fall back on NewClientFromEnv which reads config from
|
|
|
|
|
// the DOCKER_* environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and
|
|
|
|
|
// DOCKER_CERT_PATH. This allows us to lock down the config in production
|
|
|
|
|
// but also accept the standard ENV configs for dev and test.
|
|
|
|
|
dockerEndpoint := d.config.Read("docker.endpoint")
|
|
|
|
|
if dockerEndpoint != "" {
|
|
|
|
|
cert := d.config.Read("docker.tls.cert")
|
|
|
|
|
key := d.config.Read("docker.tls.key")
|
|
|
|
|
ca := d.config.Read("docker.tls.ca")
|
|
|
|
|
|
|
|
|
|
if cert+key+ca != "" {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using TLS client connection to %s", dockerEndpoint)
|
|
|
|
|
newClient, err = docker.NewTLSClient(dockerEndpoint, cert, key, ca)
|
|
|
|
|
if err != nil {
|
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
2015-12-10 21:49:29 +00:00
|
|
|
|
}
|
2018-04-05 15:47:56 +00:00
|
|
|
|
} else {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using standard client connection to %s", dockerEndpoint)
|
|
|
|
|
newClient, err = docker.NewClient(dockerEndpoint)
|
|
|
|
|
if err != nil {
|
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
2018-04-03 20:34:50 +00:00
|
|
|
|
}
|
2015-12-10 21:49:29 +00:00
|
|
|
|
}
|
2018-04-05 15:47:56 +00:00
|
|
|
|
} else {
|
2015-12-10 21:49:29 +00:00
|
|
|
|
d.logger.Println("[DEBUG] driver.docker: using client connection initialized from environment")
|
2018-04-03 20:34:50 +00:00
|
|
|
|
newClient, err = docker.NewClientFromEnv()
|
2016-06-11 18:34:41 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
|
}
|
2018-04-05 15:47:56 +00:00
|
|
|
|
}
|
2018-04-03 20:34:50 +00:00
|
|
|
|
|
2018-04-05 15:47:56 +00:00
|
|
|
|
if timeout != 0 {
|
|
|
|
|
newClient.SetTimeout(timeout)
|
|
|
|
|
}
|
2018-04-03 20:34:50 +00:00
|
|
|
|
return newClient, merr.ErrorOrNil()
|
|
|
|
|
}
|
|
|
|
|
|
2018-02-07 05:24:16 +00:00
|
|
|
|
func (d *DockerDriver) containerBinds(driverConfig *DockerDriverConfig, ctx *ExecContext,
|
2016-09-27 20:13:55 +00:00
|
|
|
|
task *structs.Task) ([]string, error) {
|
|
|
|
|
|
2018-02-07 05:24:16 +00:00
|
|
|
|
allocDirBind := fmt.Sprintf("%s:%s", ctx.TaskDir.SharedAllocDir, ctx.TaskEnv.EnvMap[env.AllocDir])
|
|
|
|
|
taskLocalBind := fmt.Sprintf("%s:%s", ctx.TaskDir.LocalDir, ctx.TaskEnv.EnvMap[env.TaskLocalDir])
|
|
|
|
|
secretDirBind := fmt.Sprintf("%s:%s", ctx.TaskDir.SecretsDir, ctx.TaskEnv.EnvMap[env.SecretsDir])
|
2016-09-27 20:13:55 +00:00
|
|
|
|
binds := []string{allocDirBind, taskLocalBind, secretDirBind}
|
2016-06-15 00:33:09 +00:00
|
|
|
|
|
2016-10-20 00:13:45 +00:00
|
|
|
|
volumesEnabled := d.config.ReadBoolDefault(dockerVolumesConfigOption, dockerVolumesConfigDefault)
|
2016-10-27 18:02:38 +00:00
|
|
|
|
|
2017-02-23 23:20:53 +00:00
|
|
|
|
if !volumesEnabled && driverConfig.VolumeDriver != "" {
|
|
|
|
|
return nil, fmt.Errorf("%s is false; cannot use volume driver %q", dockerVolumesConfigOption, driverConfig.VolumeDriver)
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-08 22:18:40 +00:00
|
|
|
|
for _, userbind := range driverConfig.Volumes {
|
2016-10-20 21:00:27 +00:00
|
|
|
|
parts := strings.Split(userbind, ":")
|
|
|
|
|
if len(parts) < 2 {
|
|
|
|
|
return nil, fmt.Errorf("invalid docker volume: %q", userbind)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Resolve dotted path segments
|
|
|
|
|
parts[0] = filepath.Clean(parts[0])
|
|
|
|
|
|
|
|
|
|
// Absolute paths aren't always supported
|
|
|
|
|
if filepath.IsAbs(parts[0]) {
|
|
|
|
|
if !volumesEnabled {
|
|
|
|
|
// Disallow mounting arbitrary absolute paths
|
|
|
|
|
return nil, fmt.Errorf("%s is false; cannot mount host paths: %+q", dockerVolumesConfigOption, userbind)
|
|
|
|
|
}
|
|
|
|
|
binds = append(binds, userbind)
|
|
|
|
|
continue
|
|
|
|
|
}
|
2016-09-27 20:13:55 +00:00
|
|
|
|
|
2016-10-20 21:00:27 +00:00
|
|
|
|
// Relative paths are always allowed as they mount within a container
|
2017-02-23 17:36:32 +00:00
|
|
|
|
// When a VolumeDriver is set, we assume we receive a binding in the format volume-name:container-dest
|
|
|
|
|
// Otherwise, we assume we receive a relative path binding in the format relative/to/task:/also/in/container
|
|
|
|
|
if driverConfig.VolumeDriver == "" {
|
|
|
|
|
// Expand path relative to alloc dir
|
2018-02-07 05:24:16 +00:00
|
|
|
|
parts[0] = filepath.Join(ctx.TaskDir.Dir, parts[0])
|
2017-02-23 17:36:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-10-20 21:00:27 +00:00
|
|
|
|
binds = append(binds, strings.Join(parts, ":"))
|
2016-09-27 20:13:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if selinuxLabel := d.config.Read(dockerSELinuxLabelConfigOption); selinuxLabel != "" {
|
|
|
|
|
// Apply SELinux Label to each volume
|
|
|
|
|
for i := range binds {
|
|
|
|
|
binds[i] = fmt.Sprintf("%s:%s", binds[i], selinuxLabel)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return binds, nil
|
2015-10-15 23:40:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-11-04 21:39:56 +00:00
|
|
|
|
// createContainerConfig initializes a struct needed to call docker.client.CreateContainer()
|
|
|
|
|
func (d *DockerDriver) createContainerConfig(ctx *ExecContext, task *structs.Task,
|
2016-02-10 15:52:15 +00:00
|
|
|
|
driverConfig *DockerDriverConfig, syslogAddr string) (docker.CreateContainerOptions, error) {
|
2015-10-15 23:40:07 +00:00
|
|
|
|
var c docker.CreateContainerOptions
|
|
|
|
|
if task.Resources == nil {
|
2015-11-17 03:55:49 +00:00
|
|
|
|
// Guard against missing resources. We should never have been able to
|
|
|
|
|
// schedule a job without specifying this.
|
2015-11-18 00:49:01 +00:00
|
|
|
|
d.logger.Println("[ERR] driver.docker: task.Resources is empty")
|
2015-11-17 03:55:49 +00:00
|
|
|
|
return c, fmt.Errorf("task.Resources is empty")
|
2015-10-15 23:40:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-02-07 05:24:16 +00:00
|
|
|
|
binds, err := d.containerBinds(driverConfig, ctx, task)
|
2015-10-15 23:40:07 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
return c, err
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-06 21:52:44 +00:00
|
|
|
|
// create the config block that will later be consumed by go-dockerclient
|
2015-11-13 01:23:04 +00:00
|
|
|
|
config := &docker.Config{
|
2017-11-29 19:33:01 +00:00
|
|
|
|
Image: d.imageID,
|
2018-01-23 22:05:00 +00:00
|
|
|
|
Entrypoint: driverConfig.Entrypoint,
|
2017-11-29 19:33:01 +00:00
|
|
|
|
Hostname: driverConfig.Hostname,
|
|
|
|
|
User: task.User,
|
|
|
|
|
Tty: driverConfig.TTY,
|
|
|
|
|
OpenStdin: driverConfig.Interactive,
|
2017-12-01 15:43:00 +00:00
|
|
|
|
StopTimeout: int(task.KillTimeout.Seconds()),
|
2017-12-07 18:46:25 +00:00
|
|
|
|
StopSignal: task.KillSignal,
|
2017-11-30 21:53:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-08-03 14:18:15 +00:00
|
|
|
|
if driverConfig.WorkDir != "" {
|
|
|
|
|
config.WorkingDir = driverConfig.WorkDir
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-28 19:17:00 +00:00
|
|
|
|
memLimit := int64(task.Resources.MemoryMB) * 1024 * 1024
|
2016-09-20 07:41:58 +00:00
|
|
|
|
|
2017-09-10 21:57:48 +00:00
|
|
|
|
if len(driverConfig.Logging) == 0 {
|
|
|
|
|
if runtime.GOOS == "darwin" {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: deferring logging to docker on Docker for Mac")
|
|
|
|
|
} else {
|
2016-10-26 00:27:13 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: Setting default logging options to syslog and %s", syslogAddr)
|
|
|
|
|
driverConfig.Logging = []DockerLoggingOpts{
|
|
|
|
|
{Type: "syslog", Config: map[string]string{"syslog-address": syslogAddr}},
|
|
|
|
|
}
|
2016-09-20 07:41:58 +00:00
|
|
|
|
}
|
2016-10-26 00:27:13 +00:00
|
|
|
|
}
|
2016-09-20 07:41:58 +00:00
|
|
|
|
|
2015-10-15 23:40:07 +00:00
|
|
|
|
hostConfig := &docker.HostConfig{
|
2015-09-09 08:08:31 +00:00
|
|
|
|
// Convert MB to bytes. This is an absolute value.
|
2017-02-21 21:21:42 +00:00
|
|
|
|
Memory: memLimit,
|
2015-09-09 08:08:31 +00:00
|
|
|
|
// Convert Mhz to shares. This is a relative value.
|
|
|
|
|
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.
|
2016-10-03 23:28:02 +00:00
|
|
|
|
Binds: binds,
|
2017-02-23 17:36:32 +00:00
|
|
|
|
|
|
|
|
|
VolumeDriver: driverConfig.VolumeDriver,
|
2016-10-26 00:27:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-02-01 20:07:05 +00:00
|
|
|
|
// Calculate CPU Quota
|
2018-03-01 00:19:51 +00:00
|
|
|
|
// cfs_quota_us is the time per core, so we must
|
|
|
|
|
// multiply the time by the number of cores available
|
|
|
|
|
// See https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/resource_management_guide/sec-cpu
|
2018-02-01 20:07:05 +00:00
|
|
|
|
if driverConfig.CPUHardLimit {
|
2018-02-27 20:32:23 +00:00
|
|
|
|
numCores := runtime.NumCPU()
|
2018-02-06 22:52:15 +00:00
|
|
|
|
percentTicks := float64(task.Resources.CPU) / float64(d.node.Resources.CPU)
|
2018-02-27 20:32:23 +00:00
|
|
|
|
hostConfig.CPUQuota = int64(percentTicks*defaultCFSPeriodUS) * int64(numCores)
|
2018-02-01 20:07:05 +00:00
|
|
|
|
}
|
2018-02-01 18:09:12 +00:00
|
|
|
|
|
2017-09-11 00:46:45 +00:00
|
|
|
|
// Windows does not support MemorySwap/MemorySwappiness #2193
|
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
|
hostConfig.MemorySwap = 0
|
|
|
|
|
hostConfig.MemorySwappiness = -1
|
|
|
|
|
} else {
|
2017-02-21 21:21:42 +00:00
|
|
|
|
hostConfig.MemorySwap = memLimit // MemorySwap is memory + swap.
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-26 00:27:13 +00:00
|
|
|
|
if len(driverConfig.Logging) != 0 {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: Using config for logging: %+v", driverConfig.Logging[0])
|
|
|
|
|
hostConfig.LogConfig = docker.LogConfig{
|
2016-09-20 07:41:58 +00:00
|
|
|
|
Type: driverConfig.Logging[0].Type,
|
|
|
|
|
Config: driverConfig.Logging[0].Config,
|
2016-10-26 00:27:13 +00:00
|
|
|
|
}
|
2015-09-26 01:22:10 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-08-21 10:51:32 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %d bytes memory for %s", hostConfig.Memory, task.Name)
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %d cpu shares for %s", hostConfig.CPUShares, task.Name)
|
2018-02-01 18:09:12 +00:00
|
|
|
|
if driverConfig.CPUHardLimit {
|
2018-02-08 00:28:43 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using %dms cpu quota and %dms cpu period for %s", hostConfig.CPUQuota, defaultCFSPeriodUS, task.Name)
|
2018-02-01 18:09:12 +00:00
|
|
|
|
}
|
2016-08-21 10:51:32 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: binding directories %#v for %s", hostConfig.Binds, task.Name)
|
2015-09-09 08:08:31 +00:00
|
|
|
|
|
2015-11-06 00:40:20 +00:00
|
|
|
|
// set privileged mode
|
2016-09-27 20:13:55 +00:00
|
|
|
|
hostPrivileged := d.config.ReadBoolDefault(dockerPrivilegedConfigOption, false)
|
2015-11-17 03:55:49 +00:00
|
|
|
|
if driverConfig.Privileged && !hostPrivileged {
|
2015-11-18 04:50:14 +00:00
|
|
|
|
return c, fmt.Errorf(`Docker privileged mode is disabled on this Nomad agent`)
|
2015-11-06 00:40:20 +00:00
|
|
|
|
}
|
2016-08-02 23:10:15 +00:00
|
|
|
|
hostConfig.Privileged = driverConfig.Privileged
|
2015-11-05 18:47:41 +00:00
|
|
|
|
|
2018-01-14 18:58:35 +00:00
|
|
|
|
// set capabilities
|
2018-01-21 11:14:24 +00:00
|
|
|
|
hostCapsWhitelistConfig := d.config.ReadDefault(
|
|
|
|
|
dockerCapsWhitelistConfigOption, dockerCapsWhitelistConfigDefault)
|
|
|
|
|
hostCapsWhitelist := make(map[string]struct{})
|
|
|
|
|
for _, cap := range strings.Split(hostCapsWhitelistConfig, ",") {
|
|
|
|
|
cap = strings.ToLower(strings.TrimSpace(cap))
|
|
|
|
|
hostCapsWhitelist[cap] = struct{}{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if _, ok := hostCapsWhitelist["all"]; !ok {
|
|
|
|
|
effectiveCaps, err := tweakCapabilities(
|
2018-01-14 18:58:35 +00:00
|
|
|
|
strings.Split(dockerBasicCaps, ","),
|
|
|
|
|
driverConfig.CapAdd,
|
|
|
|
|
driverConfig.CapDrop,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return c, err
|
|
|
|
|
}
|
|
|
|
|
var missingCaps []string
|
|
|
|
|
for _, cap := range effectiveCaps {
|
2018-01-21 11:14:24 +00:00
|
|
|
|
cap = strings.ToLower(cap)
|
|
|
|
|
if _, ok := hostCapsWhitelist[cap]; !ok {
|
2018-01-14 18:58:35 +00:00
|
|
|
|
missingCaps = append(missingCaps, cap)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if len(missingCaps) > 0 {
|
|
|
|
|
return c, fmt.Errorf("Docker driver doesn't have the following caps whitelisted on this Nomad agent: %s", missingCaps)
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-01-21 11:14:24 +00:00
|
|
|
|
|
2018-01-14 18:56:57 +00:00
|
|
|
|
hostConfig.CapAdd = driverConfig.CapAdd
|
|
|
|
|
hostConfig.CapDrop = driverConfig.CapDrop
|
|
|
|
|
|
2016-05-27 10:30:04 +00:00
|
|
|
|
// set SHM size
|
|
|
|
|
if driverConfig.ShmSize != 0 {
|
|
|
|
|
hostConfig.ShmSize = driverConfig.ShmSize
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-05 18:47:41 +00:00
|
|
|
|
// set DNS servers
|
2015-11-18 05:41:00 +00:00
|
|
|
|
for _, ip := range driverConfig.DNSServers {
|
|
|
|
|
if net.ParseIP(ip) != nil {
|
|
|
|
|
hostConfig.DNS = append(hostConfig.DNS, ip)
|
|
|
|
|
} else {
|
2015-11-18 05:43:04 +00:00
|
|
|
|
d.logger.Printf("[ERR] driver.docker: invalid ip address for container dns server: %s", ip)
|
2015-11-05 18:47:41 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-06 18:27:13 +00:00
|
|
|
|
if len(driverConfig.Devices) > 0 {
|
|
|
|
|
var devices []docker.Device
|
|
|
|
|
for _, device := range driverConfig.Devices {
|
2017-11-07 01:42:38 +00:00
|
|
|
|
dev := docker.Device{
|
|
|
|
|
PathOnHost: device.HostPath,
|
|
|
|
|
PathInContainer: device.ContainerPath,
|
|
|
|
|
CgroupPermissions: device.CgroupPermissions}
|
|
|
|
|
devices = append(devices, dev)
|
2017-11-06 18:27:13 +00:00
|
|
|
|
}
|
|
|
|
|
hostConfig.Devices = devices
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-10 16:31:53 +00:00
|
|
|
|
// Setup mounts
|
|
|
|
|
for _, m := range driverConfig.Mounts {
|
|
|
|
|
hm := docker.HostMount{
|
|
|
|
|
Target: m.Target,
|
|
|
|
|
Source: m.Source,
|
2017-08-22 21:12:44 +00:00
|
|
|
|
Type: "volume", // Only type supported
|
2017-08-10 16:31:53 +00:00
|
|
|
|
ReadOnly: m.ReadOnly,
|
|
|
|
|
}
|
2017-09-05 21:02:57 +00:00
|
|
|
|
if len(m.VolumeOptions) == 1 {
|
|
|
|
|
vo := m.VolumeOptions[0]
|
2017-08-10 16:31:53 +00:00
|
|
|
|
hm.VolumeOptions = &docker.VolumeOptions{
|
2017-09-05 21:02:57 +00:00
|
|
|
|
NoCopy: vo.NoCopy,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(vo.DriverConfig) == 1 {
|
|
|
|
|
dc := vo.DriverConfig[0]
|
|
|
|
|
hm.VolumeOptions.DriverConfig = docker.VolumeDriverConfig{
|
|
|
|
|
Name: dc.Name,
|
|
|
|
|
}
|
|
|
|
|
if len(dc.Options) == 1 {
|
|
|
|
|
hm.VolumeOptions.DriverConfig.Options = dc.Options[0]
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if len(vo.Labels) == 1 {
|
|
|
|
|
hm.VolumeOptions.Labels = vo.Labels[0]
|
2017-08-10 16:31:53 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
hostConfig.Mounts = append(hostConfig.Mounts, hm)
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-11 17:52:24 +00:00
|
|
|
|
// set DNS search domains and extra hosts
|
|
|
|
|
hostConfig.DNSSearch = driverConfig.DNSSearchDomains
|
2017-08-09 11:30:06 +00:00
|
|
|
|
hostConfig.DNSOptions = driverConfig.DNSOptions
|
2017-04-11 17:52:24 +00:00
|
|
|
|
hostConfig.ExtraHosts = driverConfig.ExtraHosts
|
2015-11-05 18:47:41 +00:00
|
|
|
|
|
2016-01-08 22:34:49 +00:00
|
|
|
|
hostConfig.IpcMode = driverConfig.IpcMode
|
|
|
|
|
hostConfig.PidMode = driverConfig.PidMode
|
|
|
|
|
hostConfig.UTSMode = driverConfig.UTSMode
|
2016-11-04 23:53:56 +00:00
|
|
|
|
hostConfig.UsernsMode = driverConfig.UsernsMode
|
2017-05-19 23:18:49 +00:00
|
|
|
|
hostConfig.SecurityOpt = driverConfig.SecurityOpt
|
2017-03-31 08:18:26 +00:00
|
|
|
|
hostConfig.Sysctls = driverConfig.Sysctl
|
|
|
|
|
hostConfig.Ulimits = driverConfig.Ulimit
|
2018-01-27 13:38:29 +00:00
|
|
|
|
hostConfig.ReadonlyRootfs = driverConfig.ReadonlyRootfs
|
2016-01-08 22:34:49 +00:00
|
|
|
|
|
2015-11-17 22:27:58 +00:00
|
|
|
|
hostConfig.NetworkMode = driverConfig.NetworkMode
|
2015-11-17 22:25:10 +00:00
|
|
|
|
if hostConfig.NetworkMode == "" {
|
2015-10-02 17:54:04 +00:00
|
|
|
|
// docker default
|
2016-08-04 21:11:06 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: networking mode not specified; defaulting to %s", defaultNetworkMode)
|
|
|
|
|
hostConfig.NetworkMode = defaultNetworkMode
|
2015-10-02 17:54:04 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-13 01:23:04 +00:00
|
|
|
|
// Setup port mapping and exposed ports
|
2015-09-24 01:01:08 +00:00
|
|
|
|
if len(task.Resources.Networks) == 0 {
|
2015-11-18 00:49:01 +00:00
|
|
|
|
d.logger.Println("[DEBUG] driver.docker: No network interfaces are available")
|
2015-11-20 05:29:37 +00:00
|
|
|
|
if len(driverConfig.PortMap) > 0 {
|
2015-11-17 22:51:38 +00:00
|
|
|
|
return c, fmt.Errorf("Trying to map ports but no network interface is available")
|
2015-11-17 03:55:49 +00:00
|
|
|
|
}
|
2015-09-24 01:01:08 +00:00
|
|
|
|
} else {
|
2015-11-13 01:23:04 +00:00
|
|
|
|
// TODO add support for more than one network
|
2015-09-24 01:01:08 +00:00
|
|
|
|
network := task.Resources.Networks[0]
|
2015-11-13 01:23:04 +00:00
|
|
|
|
publishedPorts := map[docker.Port][]docker.PortBinding{}
|
|
|
|
|
exposedPorts := map[docker.Port]struct{}{}
|
2015-09-24 01:01:08 +00:00
|
|
|
|
|
2015-11-14 02:09:42 +00:00
|
|
|
|
for _, port := range network.ReservedPorts {
|
2015-11-20 03:08:21 +00:00
|
|
|
|
// By default we will map the allocated port 1:1 to the container
|
|
|
|
|
containerPortInt := port.Value
|
|
|
|
|
|
|
|
|
|
// If the user has mapped a port using port_map we'll change it here
|
2015-11-20 05:29:37 +00:00
|
|
|
|
if mapped, ok := driverConfig.PortMap[port.Label]; ok {
|
|
|
|
|
containerPortInt = mapped
|
2015-11-20 03:08:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-18 00:31:47 +00:00
|
|
|
|
hostPortStr := strconv.Itoa(port.Value)
|
2015-11-20 03:08:21 +00:00
|
|
|
|
containerPort := docker.Port(strconv.Itoa(containerPortInt))
|
2015-11-17 03:55:49 +00:00
|
|
|
|
|
2016-07-27 21:57:40 +00:00
|
|
|
|
publishedPorts[containerPort+"/tcp"] = getPortBinding(network.IP, hostPortStr)
|
|
|
|
|
publishedPorts[containerPort+"/udp"] = getPortBinding(network.IP, hostPortStr)
|
2015-11-18 05:17:51 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (static)", network.IP, port.Value, port.Value)
|
2015-11-17 03:55:49 +00:00
|
|
|
|
|
2015-11-18 05:34:07 +00:00
|
|
|
|
exposedPorts[containerPort+"/tcp"] = struct{}{}
|
|
|
|
|
exposedPorts[containerPort+"/udp"] = struct{}{}
|
2015-11-18 05:17:51 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: exposed port %d", port.Value)
|
2015-09-24 06:45:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-14 02:09:42 +00:00
|
|
|
|
for _, port := range network.DynamicPorts {
|
2015-11-18 03:21:36 +00:00
|
|
|
|
// By default we will map the allocated port 1:1 to the container
|
2015-11-18 05:34:07 +00:00
|
|
|
|
containerPortInt := port.Value
|
2015-11-18 03:21:36 +00:00
|
|
|
|
|
|
|
|
|
// If the user has mapped a port using port_map we'll change it here
|
2015-11-20 05:29:37 +00:00
|
|
|
|
if mapped, ok := driverConfig.PortMap[port.Label]; ok {
|
|
|
|
|
containerPortInt = mapped
|
2015-09-24 01:01:08 +00:00
|
|
|
|
}
|
2015-11-17 03:55:49 +00:00
|
|
|
|
|
|
|
|
|
hostPortStr := strconv.Itoa(port.Value)
|
2015-11-19 18:15:25 +00:00
|
|
|
|
containerPort := docker.Port(strconv.Itoa(containerPortInt))
|
2015-11-17 03:55:49 +00:00
|
|
|
|
|
2016-07-27 21:57:40 +00:00
|
|
|
|
publishedPorts[containerPort+"/tcp"] = getPortBinding(network.IP, hostPortStr)
|
|
|
|
|
publishedPorts[containerPort+"/udp"] = getPortBinding(network.IP, hostPortStr)
|
2015-11-18 05:34:07 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (mapped)", network.IP, port.Value, containerPortInt)
|
2015-11-17 03:55:49 +00:00
|
|
|
|
|
2015-11-18 05:34:07 +00:00
|
|
|
|
exposedPorts[containerPort+"/tcp"] = struct{}{}
|
|
|
|
|
exposedPorts[containerPort+"/udp"] = struct{}{}
|
2015-11-20 03:08:21 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: exposed port %s", containerPort)
|
2015-09-24 01:01:08 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-13 01:23:04 +00:00
|
|
|
|
hostConfig.PortBindings = publishedPorts
|
|
|
|
|
config.ExposedPorts = exposedPorts
|
2015-09-26 01:22:10 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
|
parsedArgs := ctx.TaskEnv.ParseAndReplace(driverConfig.Args)
|
2015-10-15 23:40:07 +00:00
|
|
|
|
|
2017-01-22 22:04:41 +00:00
|
|
|
|
// If the user specified a custom command to run, we'll inject it here.
|
2015-11-17 03:29:06 +00:00
|
|
|
|
if driverConfig.Command != "" {
|
2016-02-23 18:19:40 +00:00
|
|
|
|
// Validate command
|
|
|
|
|
if err := validateCommand(driverConfig.Command, "args"); err != nil {
|
|
|
|
|
return c, err
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-17 03:29:06 +00:00
|
|
|
|
cmd := []string{driverConfig.Command}
|
2015-11-18 23:16:42 +00:00
|
|
|
|
if len(driverConfig.Args) != 0 {
|
2015-10-15 23:40:07 +00:00
|
|
|
|
cmd = append(cmd, parsedArgs...)
|
|
|
|
|
}
|
2015-11-18 05:17:51 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: setting container startup command to: %s", strings.Join(cmd, " "))
|
2015-10-15 23:40:07 +00:00
|
|
|
|
config.Cmd = cmd
|
2015-11-18 23:16:42 +00:00
|
|
|
|
} else if len(driverConfig.Args) != 0 {
|
2016-06-10 17:38:29 +00:00
|
|
|
|
config.Cmd = parsedArgs
|
2015-09-26 01:22:10 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-20 05:29:37 +00:00
|
|
|
|
if len(driverConfig.Labels) > 0 {
|
|
|
|
|
config.Labels = driverConfig.Labels
|
2015-11-18 05:17:51 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: applied labels on the container: %+v", config.Labels)
|
2015-11-17 13:12:49 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
|
config.Env = ctx.TaskEnv.List()
|
2015-11-18 04:04:10 +00:00
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
containerName := fmt.Sprintf("%s-%s", task.Name, d.DriverContext.allocID)
|
2015-11-18 05:17:51 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: setting container name to: %s", containerName)
|
2015-11-18 04:04:10 +00:00
|
|
|
|
|
2016-12-19 22:22:08 +00:00
|
|
|
|
var networkingConfig *docker.NetworkingConfig
|
2017-04-07 13:58:17 +00:00
|
|
|
|
if len(driverConfig.NetworkAliases) > 0 || driverConfig.IPv4Address != "" || driverConfig.IPv6Address != "" {
|
2016-12-19 22:22:08 +00:00
|
|
|
|
networkingConfig = &docker.NetworkingConfig{
|
|
|
|
|
EndpointsConfig: map[string]*docker.EndpointConfig{
|
2017-09-26 22:26:33 +00:00
|
|
|
|
hostConfig.NetworkMode: {},
|
2016-12-19 22:22:08 +00:00
|
|
|
|
},
|
2016-11-11 16:38:16 +00:00
|
|
|
|
}
|
2017-04-07 13:58:17 +00:00
|
|
|
|
}
|
2016-12-19 22:22:08 +00:00
|
|
|
|
|
2017-04-07 13:58:17 +00:00
|
|
|
|
if len(driverConfig.NetworkAliases) > 0 {
|
|
|
|
|
networkingConfig.EndpointsConfig[hostConfig.NetworkMode].Aliases = driverConfig.NetworkAliases
|
2016-12-19 22:22:08 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using network_mode %q with network aliases: %v",
|
|
|
|
|
hostConfig.NetworkMode, strings.Join(driverConfig.NetworkAliases, ", "))
|
2016-11-11 16:38:16 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-04-07 13:58:17 +00:00
|
|
|
|
if driverConfig.IPv4Address != "" || driverConfig.IPv6Address != "" {
|
|
|
|
|
networkingConfig.EndpointsConfig[hostConfig.NetworkMode].IPAMConfig = &docker.EndpointIPAMConfig{
|
|
|
|
|
IPv4Address: driverConfig.IPv4Address,
|
|
|
|
|
IPv6Address: driverConfig.IPv6Address,
|
|
|
|
|
}
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using network_mode %q with ipv4: %q and ipv6: %q",
|
|
|
|
|
hostConfig.NetworkMode, driverConfig.IPv4Address, driverConfig.IPv6Address)
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-17 14:41:00 +00:00
|
|
|
|
if driverConfig.MacAddress != "" {
|
|
|
|
|
config.MacAddress = driverConfig.MacAddress
|
2017-05-17 14:51:22 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using pinned mac address: %q", config.MacAddress)
|
2017-05-17 14:41:00 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-09-09 08:08:31 +00:00
|
|
|
|
return docker.CreateContainerOptions{
|
2016-11-11 16:38:16 +00:00
|
|
|
|
Name: containerName,
|
|
|
|
|
Config: config,
|
|
|
|
|
HostConfig: hostConfig,
|
|
|
|
|
NetworkingConfig: networkingConfig,
|
2015-10-13 06:57:16 +00:00
|
|
|
|
}, nil
|
2015-09-09 08:08:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-03-08 20:02:55 +00:00
|
|
|
|
func (d *DockerDriver) Periodic() (bool, time.Duration) {
|
|
|
|
|
return true, 15 * time.Second
|
|
|
|
|
}
|
|
|
|
|
|
2016-03-30 22:26:51 +00:00
|
|
|
|
// createImage creates a docker image either by pulling it from a registry or by
|
|
|
|
|
// loading it from the file system
|
2017-02-24 21:20:40 +00:00
|
|
|
|
func (d *DockerDriver) createImage(driverConfig *DockerDriverConfig, client *docker.Client, taskDir *allocdir.TaskDir) (string, error) {
|
2015-11-14 02:09:42 +00:00
|
|
|
|
image := driverConfig.ImageName
|
2018-05-14 14:36:40 +00:00
|
|
|
|
repo, tag := parseDockerImage(image)
|
2015-09-26 01:22:10 +00:00
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator, callerID := d.getDockerCoordinator(client)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
|
2015-09-26 01:22:10 +00:00
|
|
|
|
// We're going to check whether the image is already downloaded. If the tag
|
2016-12-28 18:18:38 +00:00
|
|
|
|
// is "latest", or ForcePull is set, we have to check for a new version every time so we don't
|
2015-09-26 06:28:23 +00:00
|
|
|
|
// bother to check and cache the id here. We'll download first, then cache.
|
2016-12-28 18:18:38 +00:00
|
|
|
|
if driverConfig.ForcePull {
|
2018-05-14 14:36:40 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: force pull image '%s' instead of inspecting local", dockerImageRef(repo, tag))
|
2016-12-28 18:18:38 +00:00
|
|
|
|
} else if tag != "latest" {
|
2017-01-10 21:24:45 +00:00
|
|
|
|
if dockerImage, _ := client.InspectImage(image); dockerImage != nil {
|
2017-02-24 21:20:40 +00:00
|
|
|
|
// Image exists so just increment its reference count
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator.IncrementImageReference(dockerImage.ID, image, callerID)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
return dockerImage.ID, nil
|
2017-01-10 21:24:45 +00:00
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
|
// Load the image if specified
|
2017-02-24 21:20:40 +00:00
|
|
|
|
if driverConfig.LoadImage != "" {
|
2017-01-13 01:21:54 +00:00
|
|
|
|
return d.loadImage(driverConfig, client, taskDir)
|
2017-01-10 21:24:45 +00:00
|
|
|
|
}
|
2016-03-30 22:45:17 +00:00
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
|
// Download the image
|
2017-02-24 21:20:40 +00:00
|
|
|
|
return d.pullImage(driverConfig, client, repo, tag)
|
2016-03-30 20:09:32 +00:00
|
|
|
|
}
|
2015-11-05 18:47:41 +00:00
|
|
|
|
|
2016-03-30 22:26:51 +00:00
|
|
|
|
// pullImage creates an image by pulling it from a docker registry
|
2017-02-24 21:20:40 +00:00
|
|
|
|
func (d *DockerDriver) pullImage(driverConfig *DockerDriverConfig, client *docker.Client, repo, tag string) (id string, err error) {
|
2017-05-29 10:44:13 +00:00
|
|
|
|
authOptions, err := d.resolveRegistryAuthentication(driverConfig, repo)
|
|
|
|
|
if err != nil {
|
2017-07-06 18:35:34 +00:00
|
|
|
|
if d.driverConfig.AuthSoftFail {
|
|
|
|
|
d.logger.Printf("[WARN] Failed to find docker auth for repo %q: %v", repo, err)
|
|
|
|
|
} else {
|
|
|
|
|
return "", fmt.Errorf("Failed to find docker auth for repo %q: %v", repo, err)
|
|
|
|
|
}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
if authIsEmpty(authOptions) {
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: did not find docker auth for repo %q", repo)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
2016-02-10 02:24:30 +00:00
|
|
|
|
|
2018-05-14 14:36:40 +00:00
|
|
|
|
d.emitEvent("Downloading image %s", dockerImageRef(repo, tag))
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator, callerID := d.getDockerCoordinator(client)
|
2018-04-19 17:56:24 +00:00
|
|
|
|
|
2018-04-25 21:05:14 +00:00
|
|
|
|
return coordinator.PullImage(driverConfig.ImageName, authOptions, callerID, d.emitEvent)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// authBackend encapsulates a function that resolves registry credentials.
|
2017-05-29 10:44:13 +00:00
|
|
|
|
type authBackend func(string) (*docker.AuthConfiguration, error)
|
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// resolveRegistryAuthentication attempts to retrieve auth credentials for the
|
|
|
|
|
// repo, trying all authentication-backends possible.
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func (d *DockerDriver) resolveRegistryAuthentication(driverConfig *DockerDriverConfig, repo string) (*docker.AuthConfiguration, error) {
|
|
|
|
|
return firstValidAuth(repo, []authBackend{
|
|
|
|
|
authFromTaskConfig(driverConfig),
|
|
|
|
|
authFromDockerConfig(d.config.Read("docker.auth.config")),
|
|
|
|
|
authFromHelper(d.config.Read("docker.auth.helper")),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-24 21:20:40 +00:00
|
|
|
|
// loadImage creates an image by loading it from the file system
|
|
|
|
|
func (d *DockerDriver) loadImage(driverConfig *DockerDriverConfig, client *docker.Client,
|
|
|
|
|
taskDir *allocdir.TaskDir) (id string, err error) {
|
|
|
|
|
|
|
|
|
|
archive := filepath.Join(taskDir.LocalDir, driverConfig.LoadImage)
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: loading image from: %v", archive)
|
|
|
|
|
|
|
|
|
|
f, err := os.Open(archive)
|
2016-03-30 20:09:32 +00:00
|
|
|
|
if err != nil {
|
2017-02-24 21:20:40 +00:00
|
|
|
|
return "", fmt.Errorf("unable to open image archive: %v", err)
|
2016-03-30 20:09:32 +00:00
|
|
|
|
}
|
2017-01-10 21:24:45 +00:00
|
|
|
|
|
2017-02-24 21:20:40 +00:00
|
|
|
|
if err := client.LoadImage(docker.LoadImageOptions{InputStream: f}); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
f.Close()
|
2016-03-30 20:09:32 +00:00
|
|
|
|
|
2017-02-24 21:20:40 +00:00
|
|
|
|
dockerImage, err := client.InspectImage(driverConfig.ImageName)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", recoverableErrTimeouts(err)
|
2016-03-30 20:09:32 +00:00
|
|
|
|
}
|
2017-02-24 21:20:40 +00:00
|
|
|
|
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator, callerID := d.getDockerCoordinator(client)
|
|
|
|
|
coordinator.IncrementImageReference(dockerImage.ID, driverConfig.ImageName, callerID)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
return dockerImage.ID, nil
|
2016-03-30 20:09:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-11-04 21:39:56 +00:00
|
|
|
|
// createContainer creates the container given the passed configuration. It
|
|
|
|
|
// attempts to handle any transient Docker errors.
|
2018-03-16 00:52:43 +00:00
|
|
|
|
func (d *DockerDriver) createContainer(client createContainerClient, config docker.CreateContainerOptions) (*docker.Container, error) {
|
2016-11-04 21:39:56 +00:00
|
|
|
|
// Create a container
|
2016-11-30 23:59:47 +00:00
|
|
|
|
attempted := 0
|
2016-11-04 21:39:56 +00:00
|
|
|
|
CREATE:
|
2016-11-30 23:59:47 +00:00
|
|
|
|
container, createErr := client.CreateContainer(config)
|
|
|
|
|
if createErr == nil {
|
2016-11-04 21:39:56 +00:00
|
|
|
|
return container, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-13 20:46:55 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: failed to create container %q from image %q (ID: %q) (attempt %d): %v",
|
|
|
|
|
config.Name, d.driverConfig.ImageName, d.imageID, attempted+1, createErr)
|
2018-03-16 00:52:43 +00:00
|
|
|
|
|
|
|
|
|
// Volume management tools like Portworx may not have detached a volume
|
|
|
|
|
// from a previous node before Nomad started a task replacement task.
|
|
|
|
|
// Treat these errors as recoverable so we retry.
|
|
|
|
|
if strings.Contains(strings.ToLower(createErr.Error()), "volume is attached on another node") {
|
|
|
|
|
return nil, structs.NewRecoverableError(createErr, true)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If the container already exists determine whether it's already
|
|
|
|
|
// running or if it's dead and needs to be recreated.
|
2016-11-30 23:59:47 +00:00
|
|
|
|
if strings.Contains(strings.ToLower(createErr.Error()), "container already exists") {
|
2016-11-29 01:37:22 +00:00
|
|
|
|
containers, err := client.ListContainers(docker.ListContainersOptions{
|
|
|
|
|
All: true,
|
|
|
|
|
})
|
2016-11-04 21:39:56 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed to query list of containers matching name:%s", config.Name)
|
2016-11-30 23:59:47 +00:00
|
|
|
|
return nil, recoverableErrTimeouts(fmt.Errorf("Failed to query list of containers: %s", err))
|
2016-11-04 21:39:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Delete matching containers
|
2016-11-29 01:37:22 +00:00
|
|
|
|
// Adding a / infront of the container name since Docker returns the
|
|
|
|
|
// container names with a / pre-pended to the Nomad generated container names
|
|
|
|
|
containerName := "/" + config.Name
|
2016-11-29 22:29:37 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: searching for container name %q to purge", containerName)
|
2017-07-07 21:55:57 +00:00
|
|
|
|
for _, shimContainer := range containers {
|
2017-08-31 18:28:13 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: listed container %+v", shimContainer.Names)
|
2016-11-04 21:39:56 +00:00
|
|
|
|
found := false
|
2017-07-07 21:55:57 +00:00
|
|
|
|
for _, name := range shimContainer.Names {
|
2016-11-29 01:37:22 +00:00
|
|
|
|
if name == containerName {
|
2017-08-31 18:28:13 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: Found container %v: %v", containerName, shimContainer.ID)
|
2016-11-04 21:39:56 +00:00
|
|
|
|
found = true
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if !found {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-30 00:29:30 +00:00
|
|
|
|
// Inspect the container and if the container isn't dead then return
|
|
|
|
|
// the container
|
2017-07-07 21:55:57 +00:00
|
|
|
|
container, err := client.InspectContainer(shimContainer.ID)
|
2016-11-30 00:29:30 +00:00
|
|
|
|
if err != nil {
|
2017-07-07 21:55:57 +00:00
|
|
|
|
err = fmt.Errorf("Failed to inspect container %s: %s", shimContainer.ID, err)
|
|
|
|
|
|
|
|
|
|
// This error is always recoverable as it could
|
|
|
|
|
// be caused by races between listing
|
|
|
|
|
// containers and this container being removed.
|
|
|
|
|
// See #2802
|
|
|
|
|
return nil, structs.NewRecoverableError(err, true)
|
2016-11-30 00:29:30 +00:00
|
|
|
|
}
|
2017-08-31 18:28:13 +00:00
|
|
|
|
if container != nil && container.State.Running {
|
2016-11-30 00:29:30 +00:00
|
|
|
|
return container, nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-04 21:39:56 +00:00
|
|
|
|
err = client.RemoveContainer(docker.RemoveContainerOptions{
|
2016-11-30 00:29:30 +00:00
|
|
|
|
ID: container.ID,
|
|
|
|
|
Force: true,
|
2016-11-04 21:39:56 +00:00
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed to purge container %s", container.ID)
|
2016-11-30 23:59:47 +00:00
|
|
|
|
return nil, recoverableErrTimeouts(fmt.Errorf("Failed to purge container %s: %s", container.ID, err))
|
2016-11-04 21:39:56 +00:00
|
|
|
|
} else if err == nil {
|
|
|
|
|
d.logger.Printf("[INFO] driver.docker: purged container %s", container.ID)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if attempted < 5 {
|
|
|
|
|
attempted++
|
2016-11-26 03:22:58 +00:00
|
|
|
|
time.Sleep(1 * time.Second)
|
2016-11-04 21:39:56 +00:00
|
|
|
|
goto CREATE
|
|
|
|
|
}
|
2017-03-01 02:19:13 +00:00
|
|
|
|
} else if strings.Contains(strings.ToLower(createErr.Error()), "no such image") {
|
|
|
|
|
// There is still a very small chance this is possible even with the
|
|
|
|
|
// coordinator so retry.
|
2017-03-14 23:33:36 +00:00
|
|
|
|
return nil, structs.NewRecoverableError(createErr, true)
|
2016-11-04 21:39:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-11-30 23:59:47 +00:00
|
|
|
|
return nil, recoverableErrTimeouts(createErr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// startContainer starts the passed container. It attempts to handle any
|
|
|
|
|
// transient Docker errors.
|
2017-01-14 00:46:08 +00:00
|
|
|
|
func (d *DockerDriver) startContainer(c *docker.Container) error {
|
2016-11-30 23:59:47 +00:00
|
|
|
|
// Start a container
|
|
|
|
|
attempted := 0
|
|
|
|
|
START:
|
|
|
|
|
startErr := client.StartContainer(c.ID, c.HostConfig)
|
|
|
|
|
if startErr == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: failed to start container %q (attempt %d): %v", c.ID, attempted+1, startErr)
|
|
|
|
|
|
|
|
|
|
// If it is a 500 error it is likely we can retry and be successful
|
|
|
|
|
if strings.Contains(startErr.Error(), "API error (500)") {
|
|
|
|
|
if attempted < 5 {
|
|
|
|
|
attempted++
|
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
|
goto START
|
|
|
|
|
}
|
2017-08-22 13:03:31 +00:00
|
|
|
|
return structs.NewRecoverableError(startErr, true)
|
2016-11-30 23:59:47 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return recoverableErrTimeouts(startErr)
|
2016-11-04 21:39:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
func (d *DockerDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
|
|
|
|
|
// 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-11-18 01:12:45 +00:00
|
|
|
|
if err := json.Unmarshal(pidBytes, pid); err != nil {
|
2015-09-03 10:38:36 +00:00
|
|
|
|
return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
|
|
|
|
|
}
|
2016-02-12 21:33:09 +00:00
|
|
|
|
d.logger.Printf("[INFO] driver.docker: re-attaching to docker process: %s", pid.ContainerID)
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: re-attached to handle: %s", handleID)
|
2016-02-10 18:18:14 +00:00
|
|
|
|
pluginConfig := &plugin.ClientConfig{
|
|
|
|
|
Reattach: pid.PluginConfig.PluginConfig(),
|
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
2016-06-11 18:34:41 +00:00
|
|
|
|
client, waitClient, err := d.dockerClients()
|
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{
|
2017-09-26 22:26:33 +00:00
|
|
|
|
"id": {pid.ContainerID},
|
2015-09-26 06:13:40 +00:00
|
|
|
|
},
|
|
|
|
|
})
|
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 {
|
2016-08-17 20:48:14 +00:00
|
|
|
|
return nil, fmt.Errorf("Failed to find container %s", pid.ContainerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
2017-01-12 19:50:49 +00:00
|
|
|
|
exec, pluginClient, err := createExecutorWithConfig(pluginConfig, d.config.LogOutput)
|
2016-02-11 00:40:36 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
d.logger.Printf("[INFO] driver.docker: couldn't re-attach to the plugin process: %v", err)
|
2016-06-17 18:52:44 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: stopping container %q", pid.ContainerID)
|
2016-06-28 12:26:47 +00:00
|
|
|
|
if e := client.StopContainer(pid.ContainerID, uint(pid.KillTimeout.Seconds())); e != nil {
|
2016-02-11 00:40:36 +00:00
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: couldn't stop container: %v", e)
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
|
|
2016-03-30 05:05:02 +00:00
|
|
|
|
ver, _ := exec.Version()
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: version of executor: %v", ver.Version)
|
2016-03-29 23:27:31 +00:00
|
|
|
|
|
2017-02-24 21:20:40 +00:00
|
|
|
|
// Increment the reference count since we successfully attached to this
|
|
|
|
|
// container
|
2017-03-26 00:05:53 +00:00
|
|
|
|
coordinator, callerID := d.getDockerCoordinator(client)
|
|
|
|
|
coordinator.IncrementImageReference(pid.ImageID, pid.Image, callerID)
|
2017-02-24 21:20:40 +00:00
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
// Return a driver handle
|
2015-11-19 22:20:41 +00:00
|
|
|
|
h := &DockerHandle{
|
2016-04-14 18:05:20 +00:00
|
|
|
|
client: client,
|
2016-06-11 18:34:41 +00:00
|
|
|
|
waitClient: waitClient,
|
2016-04-14 18:05:20 +00:00
|
|
|
|
executor: exec,
|
|
|
|
|
pluginClient: pluginClient,
|
|
|
|
|
logger: d.logger,
|
2017-02-27 21:49:54 +00:00
|
|
|
|
Image: pid.Image,
|
|
|
|
|
ImageID: pid.ImageID,
|
2016-04-14 18:05:20 +00:00
|
|
|
|
containerID: pid.ContainerID,
|
|
|
|
|
version: pid.Version,
|
|
|
|
|
killTimeout: pid.KillTimeout,
|
|
|
|
|
maxKillTimeout: pid.MaxKillTimeout,
|
2016-05-26 18:52:01 +00:00
|
|
|
|
doneCh: make(chan bool),
|
2016-06-12 03:15:50 +00:00
|
|
|
|
waitCh: make(chan *dstructs.WaitResult, 1),
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
2016-06-10 02:45:41 +00:00
|
|
|
|
go h.collectStats()
|
2015-09-03 10:38:36 +00:00
|
|
|
|
go h.run()
|
|
|
|
|
return h, nil
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-19 22:20:41 +00:00
|
|
|
|
func (h *DockerHandle) ID() string {
|
2015-09-03 10:38:36 +00:00
|
|
|
|
// Return a handle to the PID
|
|
|
|
|
pid := dockerPID{
|
2016-03-03 17:21:21 +00:00
|
|
|
|
Version: h.version,
|
|
|
|
|
ContainerID: h.containerID,
|
2017-02-24 21:20:40 +00:00
|
|
|
|
Image: h.Image,
|
|
|
|
|
ImageID: h.ImageID,
|
2016-03-03 17:21:21 +00:00
|
|
|
|
KillTimeout: h.killTimeout,
|
|
|
|
|
MaxKillTimeout: h.maxKillTimeout,
|
|
|
|
|
PluginConfig: NewPluginReattachConfig(h.pluginClient.ReattachConfig()),
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
data, err := json.Marshal(pid)
|
|
|
|
|
if err != nil {
|
2015-11-18 05:17:51 +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))
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-19 22:20:41 +00:00
|
|
|
|
func (h *DockerHandle) ContainerID() string {
|
2015-11-19 21:57:18 +00:00
|
|
|
|
return h.containerID
|
|
|
|
|
}
|
|
|
|
|
|
2016-06-12 03:15:50 +00:00
|
|
|
|
func (h *DockerHandle) WaitCh() chan *dstructs.WaitResult {
|
2015-09-03 10:38:36 +00:00
|
|
|
|
return h.waitCh
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-19 22:20:41 +00:00
|
|
|
|
func (h *DockerHandle) Update(task *structs.Task) error {
|
2016-02-04 03:43:44 +00:00
|
|
|
|
// Store the updated kill timeout.
|
2016-03-03 17:21:21 +00:00
|
|
|
|
h.killTimeout = GetKillTimeout(task.KillTimeout, h.maxKillTimeout)
|
2016-03-17 09:53:31 +00:00
|
|
|
|
if err := h.executor.UpdateTask(task); err != nil {
|
2016-02-11 22:44:35 +00:00
|
|
|
|
h.logger.Printf("[DEBUG] driver.docker: failed to update log config: %v", err)
|
|
|
|
|
}
|
2016-02-04 03:43:44 +00:00
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
// Update is not possible
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-01 00:43:57 +00:00
|
|
|
|
func (h *DockerHandle) Exec(ctx context.Context, cmd string, args []string) ([]byte, int, error) {
|
|
|
|
|
fullCmd := make([]string, len(args)+1)
|
|
|
|
|
fullCmd[0] = cmd
|
|
|
|
|
copy(fullCmd[1:], args)
|
|
|
|
|
createExecOpts := docker.CreateExecOptions{
|
|
|
|
|
AttachStdin: false,
|
|
|
|
|
AttachStdout: true,
|
|
|
|
|
AttachStderr: true,
|
|
|
|
|
Tty: false,
|
|
|
|
|
Cmd: fullCmd,
|
|
|
|
|
Container: h.containerID,
|
|
|
|
|
Context: ctx,
|
|
|
|
|
}
|
|
|
|
|
exec, err := h.client.CreateExec(createExecOpts)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
output, _ := circbuf.NewBuffer(int64(dstructs.CheckBufSize))
|
|
|
|
|
startOpts := docker.StartExecOptions{
|
|
|
|
|
Detach: false,
|
|
|
|
|
Tty: false,
|
|
|
|
|
OutputStream: output,
|
|
|
|
|
ErrorStream: output,
|
|
|
|
|
Context: ctx,
|
|
|
|
|
}
|
|
|
|
|
if err := client.StartExec(exec.ID, startOpts); err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
res, err := client.InspectExec(exec.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return output.Bytes(), 0, err
|
|
|
|
|
}
|
|
|
|
|
return output.Bytes(), res.ExitCode, nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-07 19:37:52 +00:00
|
|
|
|
func (h *DockerHandle) Signal(s os.Signal) error {
|
|
|
|
|
// Convert types
|
|
|
|
|
sysSig, ok := s.(syscall.Signal)
|
|
|
|
|
if !ok {
|
|
|
|
|
return fmt.Errorf("Failed to determine signal number")
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-18 20:43:26 +00:00
|
|
|
|
// TODO When we expose signals we will need a mapping layer that converts
|
|
|
|
|
// MacOS signals to the correct signal number for docker. Or we change the
|
|
|
|
|
// interface to take a signal string and leave it up to driver to map?
|
|
|
|
|
|
2016-10-07 19:37:52 +00:00
|
|
|
|
dockerSignal := docker.Signal(sysSig)
|
|
|
|
|
opts := docker.KillContainerOptions{
|
|
|
|
|
ID: h.containerID,
|
|
|
|
|
Signal: dockerSignal,
|
|
|
|
|
}
|
|
|
|
|
return h.client.KillContainer(opts)
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-23 00:10:30 +00:00
|
|
|
|
// Kill is used to terminate the task. This uses `docker stop -t killTimeout`
|
2015-11-19 22:20:41 +00:00
|
|
|
|
func (h *DockerHandle) Kill() error {
|
2015-09-03 10:38:36 +00:00
|
|
|
|
// Stop the container
|
2015-12-23 00:10:30 +00:00
|
|
|
|
err := h.client.StopContainer(h.containerID, uint(h.killTimeout.Seconds()))
|
2015-09-03 10:38:36 +00:00
|
|
|
|
if err != nil {
|
2016-04-12 04:51:20 +00:00
|
|
|
|
h.executor.Exit()
|
|
|
|
|
h.pluginClient.Kill()
|
|
|
|
|
|
2016-03-03 00:27:01 +00:00
|
|
|
|
// Container has already been removed.
|
|
|
|
|
if strings.Contains(err.Error(), NoSuchContainerError) {
|
2018-03-12 18:26:37 +00:00
|
|
|
|
h.logger.Printf("[DEBUG] driver.docker: attempted to stop nonexistent container %s", h.containerID)
|
2016-03-03 00:27:01 +00:00
|
|
|
|
return nil
|
|
|
|
|
}
|
2016-01-20 20:00:20 +00:00
|
|
|
|
h.logger.Printf("[ERR] driver.docker: failed to stop container %s: %v", h.containerID, err)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
return fmt.Errorf("Failed to stop container %s: %s", h.containerID, err)
|
|
|
|
|
}
|
2015-12-11 23:02:13 +00:00
|
|
|
|
h.logger.Printf("[INFO] driver.docker: stopped container %s", h.containerID)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-28 23:06:01 +00:00
|
|
|
|
func (h *DockerHandle) Stats() (*cstructs.TaskResourceUsage, error) {
|
2016-05-25 19:36:37 +00:00
|
|
|
|
h.resourceUsageLock.RLock()
|
|
|
|
|
defer h.resourceUsageLock.RUnlock()
|
2016-06-07 01:52:54 +00:00
|
|
|
|
var err error
|
|
|
|
|
if h.resourceUsage == nil {
|
|
|
|
|
err = fmt.Errorf("stats collection hasn't started yet")
|
|
|
|
|
}
|
|
|
|
|
return h.resourceUsage, err
|
2016-04-28 23:06:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-11-19 22:20:41 +00:00
|
|
|
|
func (h *DockerHandle) run() {
|
2015-09-03 10:38:36 +00:00
|
|
|
|
// Wait for it...
|
2016-11-04 21:39:56 +00:00
|
|
|
|
exitCode, werr := h.waitClient.WaitContainer(h.containerID)
|
|
|
|
|
if werr != nil {
|
2015-11-18 05:17:51 +00:00
|
|
|
|
h.logger.Printf("[ERR] driver.docker: failed 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 {
|
2016-11-04 21:39:56 +00:00
|
|
|
|
werr = fmt.Errorf("Docker container exited with non-zero exit code: %d", exitCode)
|
2015-09-26 05:43:19 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-10-27 15:45:06 +00:00
|
|
|
|
container, ierr := h.waitClient.InspectContainer(h.containerID)
|
|
|
|
|
if ierr != nil {
|
|
|
|
|
h.logger.Printf("[ERR] driver.docker: failed to inspect container %s: %v", h.containerID, ierr)
|
|
|
|
|
} else if container.State.OOMKilled {
|
2017-10-27 18:30:52 +00:00
|
|
|
|
werr = fmt.Errorf("OOM Killed")
|
2017-10-27 15:45:06 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
|
close(h.doneCh)
|
2016-02-10 02:24:30 +00:00
|
|
|
|
|
|
|
|
|
// Shutdown the syslog collector
|
2016-03-17 09:53:31 +00:00
|
|
|
|
if err := h.executor.Exit(); err != nil {
|
2016-02-10 02:24:30 +00:00
|
|
|
|
h.logger.Printf("[ERR] driver.docker: failed to kill the syslog collector: %v", err)
|
|
|
|
|
}
|
|
|
|
|
h.pluginClient.Kill()
|
2016-04-12 04:51:20 +00:00
|
|
|
|
|
|
|
|
|
// Stop the container just incase the docker daemon's wait returned
|
|
|
|
|
// incorrectly
|
|
|
|
|
if err := h.client.StopContainer(h.containerID, 0); err != nil {
|
2016-04-12 09:29:28 +00:00
|
|
|
|
_, noSuchContainer := err.(*docker.NoSuchContainer)
|
|
|
|
|
_, containerNotRunning := err.(*docker.ContainerNotRunning)
|
|
|
|
|
if !containerNotRunning && !noSuchContainer {
|
|
|
|
|
h.logger.Printf("[ERR] driver.docker: error stopping container: %v", err)
|
|
|
|
|
}
|
2016-04-12 04:51:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Remove the container
|
2016-08-04 06:13:50 +00:00
|
|
|
|
if err := h.client.RemoveContainer(docker.RemoveContainerOptions{ID: h.containerID, RemoveVolumes: true, Force: true}); err != nil {
|
2016-04-12 04:51:20 +00:00
|
|
|
|
h.logger.Printf("[ERR] driver.docker: error removing container: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-04 21:58:55 +00:00
|
|
|
|
// Send the results
|
2016-11-04 21:39:56 +00:00
|
|
|
|
h.waitCh <- dstructs.NewWaitResult(exitCode, 0, werr)
|
|
|
|
|
close(h.waitCh)
|
2015-09-03 10:38:36 +00:00
|
|
|
|
}
|
2016-05-19 17:05:40 +00:00
|
|
|
|
|
2016-05-25 19:36:37 +00:00
|
|
|
|
// collectStats starts collecting resource usage stats of a docker container
|
|
|
|
|
func (h *DockerHandle) collectStats() {
|
|
|
|
|
statsCh := make(chan *docker.Stats)
|
2016-05-26 18:52:01 +00:00
|
|
|
|
statsOpts := docker.StatsOptions{ID: h.containerID, Done: h.doneCh, Stats: statsCh, Stream: true}
|
|
|
|
|
go func() {
|
|
|
|
|
//TODO handle Stats error
|
2016-06-11 18:34:41 +00:00
|
|
|
|
if err := h.waitClient.Stats(statsOpts); err != nil {
|
2016-05-26 18:52:01 +00:00
|
|
|
|
h.logger.Printf("[DEBUG] driver.docker: error collecting stats from container %s: %v", h.containerID, err)
|
|
|
|
|
}
|
|
|
|
|
}()
|
2016-06-12 16:08:35 +00:00
|
|
|
|
numCores := runtime.NumCPU()
|
2016-05-19 17:05:40 +00:00
|
|
|
|
for {
|
|
|
|
|
select {
|
2016-05-25 19:36:37 +00:00
|
|
|
|
case s := <-statsCh:
|
2016-05-19 17:05:40 +00:00
|
|
|
|
if s != nil {
|
|
|
|
|
ms := &cstructs.MemoryStats{
|
|
|
|
|
RSS: s.MemoryStats.Stats.Rss,
|
|
|
|
|
Cache: s.MemoryStats.Stats.Cache,
|
|
|
|
|
Swap: s.MemoryStats.Stats.Swap,
|
|
|
|
|
MaxUsage: s.MemoryStats.MaxUsage,
|
2016-06-10 02:45:41 +00:00
|
|
|
|
Measured: DockerMeasuredMemStats,
|
2016-05-19 17:05:40 +00:00
|
|
|
|
}
|
2016-05-19 20:32:03 +00:00
|
|
|
|
|
2016-05-21 07:49:17 +00:00
|
|
|
|
cs := &cstructs.CpuStats{
|
2016-05-19 20:32:03 +00:00
|
|
|
|
ThrottledPeriods: s.CPUStats.ThrottlingData.ThrottledPeriods,
|
|
|
|
|
ThrottledTime: s.CPUStats.ThrottlingData.ThrottledTime,
|
2016-06-10 02:45:41 +00:00
|
|
|
|
Measured: DockerMeasuredCpuStats,
|
2016-05-19 20:32:03 +00:00
|
|
|
|
}
|
2016-06-10 02:45:41 +00:00
|
|
|
|
|
2016-05-19 20:32:03 +00:00
|
|
|
|
// Calculate percentage
|
2016-06-10 17:38:29 +00:00
|
|
|
|
cs.Percent = calculatePercent(
|
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage,
|
2017-09-16 04:43:03 +00:00
|
|
|
|
s.CPUStats.SystemCPUUsage, s.PreCPUStats.SystemCPUUsage, numCores)
|
2016-06-10 17:38:29 +00:00
|
|
|
|
cs.SystemMode = calculatePercent(
|
|
|
|
|
s.CPUStats.CPUUsage.UsageInKernelmode, s.PreCPUStats.CPUUsage.UsageInKernelmode,
|
2017-09-16 04:43:03 +00:00
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, numCores)
|
2016-06-10 17:38:29 +00:00
|
|
|
|
cs.UserMode = calculatePercent(
|
|
|
|
|
s.CPUStats.CPUUsage.UsageInUsermode, s.PreCPUStats.CPUUsage.UsageInUsermode,
|
2017-09-16 04:43:03 +00:00
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, numCores)
|
2016-06-12 16:08:35 +00:00
|
|
|
|
cs.TotalTicks = (cs.Percent / 100) * shelpers.TotalTicksAvailable() / float64(numCores)
|
2016-06-10 21:32:45 +00:00
|
|
|
|
|
2016-05-25 19:36:37 +00:00
|
|
|
|
h.resourceUsageLock.Lock()
|
2016-05-21 09:05:08 +00:00
|
|
|
|
h.resourceUsage = &cstructs.TaskResourceUsage{
|
|
|
|
|
ResourceUsage: &cstructs.ResourceUsage{
|
|
|
|
|
MemoryStats: ms,
|
|
|
|
|
CpuStats: cs,
|
|
|
|
|
},
|
2016-05-27 21:15:51 +00:00
|
|
|
|
Timestamp: s.Read.UTC().UnixNano(),
|
2016-05-21 09:05:08 +00:00
|
|
|
|
}
|
2016-05-25 19:36:37 +00:00
|
|
|
|
h.resourceUsageLock.Unlock()
|
2016-05-19 17:05:40 +00:00
|
|
|
|
}
|
|
|
|
|
case <-h.doneCh:
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-06-10 17:38:29 +00:00
|
|
|
|
|
|
|
|
|
func calculatePercent(newSample, oldSample, newTotal, oldTotal uint64, cores int) float64 {
|
|
|
|
|
numerator := newSample - oldSample
|
|
|
|
|
denom := newTotal - oldTotal
|
|
|
|
|
if numerator <= 0 || denom <= 0 {
|
|
|
|
|
return 0.0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return (float64(numerator) / float64(denom)) * float64(cores) * 100.0
|
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// loadDockerConfig loads the docker config at the specified path, returning an
|
|
|
|
|
// error if it couldn't be read.
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func loadDockerConfig(file string) (*configfile.ConfigFile, error) {
|
|
|
|
|
f, err := os.Open(file)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("Failed to open auth config file: %v, error: %v", file, err)
|
|
|
|
|
}
|
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
|
|
cfile := new(configfile.ConfigFile)
|
|
|
|
|
if err = cfile.LoadFromReader(f); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("Failed to parse auth config file: %v", err)
|
|
|
|
|
}
|
|
|
|
|
return cfile, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// parseRepositoryInfo takes a repo and returns the Docker RepositoryInfo. This
|
|
|
|
|
// is useful for interacting with a Docker config object.
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func parseRepositoryInfo(repo string) (*registry.RepositoryInfo, error) {
|
2017-01-12 19:22:35 +00:00
|
|
|
|
name, err := reference.ParseNamed(repo)
|
|
|
|
|
if err != nil {
|
2017-02-28 00:00:19 +00:00
|
|
|
|
return nil, fmt.Errorf("Failed to parse named repo %q: %v", repo, err)
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
repoInfo, err := registry.ParseRepositoryInfo(name)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("Failed to parse repository: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
return repoInfo, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// firstValidAuth tries a list of auth backends, returning first error or AuthConfiguration
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func firstValidAuth(repo string, backends []authBackend) (*docker.AuthConfiguration, error) {
|
|
|
|
|
for _, backend := range backends {
|
|
|
|
|
auth, err := backend(repo)
|
|
|
|
|
if auth != nil || err != nil {
|
|
|
|
|
return auth, err
|
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// authFromTaskConfig generates an authBackend for any auth given in the task-configuration
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func authFromTaskConfig(driverConfig *DockerDriverConfig) authBackend {
|
|
|
|
|
return func(string) (*docker.AuthConfiguration, error) {
|
|
|
|
|
if len(driverConfig.Auth) == 0 {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
auth := driverConfig.Auth[0]
|
|
|
|
|
return &docker.AuthConfiguration{
|
|
|
|
|
Username: auth.Username,
|
|
|
|
|
Password: auth.Password,
|
|
|
|
|
Email: auth.Email,
|
|
|
|
|
ServerAddress: auth.ServerAddress,
|
|
|
|
|
}, nil
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// authFromDockerConfig generate an authBackend for a dockercfg-compatible file.
|
|
|
|
|
// The authBacken can either be from explicit auth definitions or via credential
|
|
|
|
|
// helpers
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func authFromDockerConfig(file string) authBackend {
|
|
|
|
|
return func(repo string) (*docker.AuthConfiguration, error) {
|
|
|
|
|
if file == "" {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
repoInfo, err := parseRepositoryInfo(repo)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
cfile, err := loadDockerConfig(file)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return firstValidAuth(repo, []authBackend{
|
|
|
|
|
func(string) (*docker.AuthConfiguration, error) {
|
|
|
|
|
dockerAuthConfig := registry.ResolveAuthConfig(cfile.AuthConfigs, repoInfo.Index)
|
|
|
|
|
auth := &docker.AuthConfiguration{
|
|
|
|
|
Username: dockerAuthConfig.Username,
|
|
|
|
|
Password: dockerAuthConfig.Password,
|
|
|
|
|
Email: dockerAuthConfig.Email,
|
|
|
|
|
ServerAddress: dockerAuthConfig.ServerAddress,
|
|
|
|
|
}
|
|
|
|
|
if authIsEmpty(auth) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return auth, nil
|
|
|
|
|
},
|
|
|
|
|
authFromHelper(cfile.CredentialHelpers[registry.GetAuthConfigKey(repoInfo.Index)]),
|
|
|
|
|
authFromHelper(cfile.CredentialsStore),
|
|
|
|
|
})
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// authFromHelper generates an authBackend for a docker-credentials-helper;
|
|
|
|
|
// A script taking the requested domain on input, outputting JSON with
|
|
|
|
|
// "Username" and "Secret"
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func authFromHelper(helperName string) authBackend {
|
|
|
|
|
return func(repo string) (*docker.AuthConfiguration, error) {
|
|
|
|
|
if helperName == "" {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
helper := dockerAuthHelperPrefix + helperName
|
|
|
|
|
cmd := exec.Command(helper, "get")
|
2017-09-05 23:32:40 +00:00
|
|
|
|
|
|
|
|
|
// Ensure that the HTTPs prefix exists
|
|
|
|
|
if !strings.HasPrefix(repo, "https://") {
|
|
|
|
|
repo = fmt.Sprintf("https://%s", repo)
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
cmd.Stdin = strings.NewReader(repo)
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
output, err := cmd.Output()
|
|
|
|
|
if err != nil {
|
2017-09-05 23:32:40 +00:00
|
|
|
|
switch err.(type) {
|
2017-05-29 10:44:13 +00:00
|
|
|
|
default:
|
|
|
|
|
return nil, err
|
|
|
|
|
case *exec.ExitError:
|
2017-09-05 23:32:40 +00:00
|
|
|
|
return nil, fmt.Errorf("%s with input %q failed with stderr: %s", helper, repo, output)
|
2017-05-29 10:44:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-29 10:44:13 +00:00
|
|
|
|
var response map[string]string
|
|
|
|
|
if err := json.Unmarshal(output, &response); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
auth := &docker.AuthConfiguration{
|
|
|
|
|
Username: response["Username"],
|
|
|
|
|
Password: response["Secret"],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if authIsEmpty(auth) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return auth, nil
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
2017-05-29 10:44:13 +00:00
|
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
2017-05-31 22:56:54 +00:00
|
|
|
|
// authIsEmpty returns if auth is nil or an empty structure
|
2017-05-29 10:44:13 +00:00
|
|
|
|
func authIsEmpty(auth *docker.AuthConfiguration) bool {
|
|
|
|
|
if auth == nil {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
return auth.Username == "" &&
|
|
|
|
|
auth.Password == "" &&
|
|
|
|
|
auth.Email == "" &&
|
|
|
|
|
auth.ServerAddress == ""
|
2017-01-12 19:22:35 +00:00
|
|
|
|
}
|
2018-03-16 00:52:43 +00:00
|
|
|
|
|
|
|
|
|
// createContainerClient is the subset of Docker Client methods used by the
|
|
|
|
|
// createContainer method to ease testing subtle error conditions.
|
|
|
|
|
type createContainerClient interface {
|
|
|
|
|
CreateContainer(docker.CreateContainerOptions) (*docker.Container, error)
|
|
|
|
|
InspectContainer(id string) (*docker.Container, error)
|
|
|
|
|
ListContainers(docker.ListContainersOptions) ([]docker.APIContainers, error)
|
|
|
|
|
RemoveContainer(opts docker.RemoveContainerOptions) error
|
|
|
|
|
}
|
2018-05-14 14:36:40 +00:00
|
|
|
|
|
|
|
|
|
func parseDockerImage(image string) (repo, tag string) {
|
|
|
|
|
repo, tag = docker.ParseRepositoryTag(image)
|
|
|
|
|
if tag == "" {
|
|
|
|
|
if i := strings.IndexRune(image, '@'); i > -1 { // Has digest (@sha256:...)
|
|
|
|
|
// when pulling images with a digest, the repository contains the sha hash, and the tag is empty
|
|
|
|
|
// see: https://github.com/fsouza/go-dockerclient/blob/master/image_test.go#L471
|
|
|
|
|
repo = image
|
|
|
|
|
} else {
|
|
|
|
|
tag = "latest"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func dockerImageRef(repo string, tag string) string {
|
|
|
|
|
if tag == "" {
|
|
|
|
|
return repo
|
|
|
|
|
}
|
|
|
|
|
return fmt.Sprintf("%s:%s", repo, tag)
|
|
|
|
|
}
|