2015-09-03 10:38:36 +00:00
|
|
|
package driver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2015-11-05 18:47:41 +00:00
|
|
|
"net"
|
2016-02-06 13:43:30 +00:00
|
|
|
"os"
|
2015-10-15 23:40:07 +00:00
|
|
|
"path/filepath"
|
2016-02-29 00:56:05 +00:00
|
|
|
"regexp"
|
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
|
|
|
|
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"
|
2015-09-03 10:38:36 +00:00
|
|
|
"github.com/hashicorp/nomad/client/config"
|
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"
|
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 (
|
2016-06-11 18:34:41 +00:00
|
|
|
// We store the clients globally to cache the connection to the docker daemon.
|
|
|
|
createClients sync.Once
|
|
|
|
|
|
|
|
// client is a docker client with a timeout of 1 minute. This is for doing
|
|
|
|
// 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
|
|
|
|
|
|
|
// 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") ||
|
|
|
|
strings.Contains(err.Error(), "EOF") {
|
|
|
|
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
|
|
|
|
|
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
|
|
|
|
|
|
|
// dockerImageResKey is the CreatedResources key for docker images
|
|
|
|
dockerImageResKey = "image"
|
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
|
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:"-"`
|
|
|
|
}
|
|
|
|
|
2015-11-14 04:22:49 +00:00
|
|
|
type DockerDriverConfig struct {
|
2015-11-18 05:41:00 +00:00
|
|
|
ImageName string `mapstructure:"image"` // Container's Image Name
|
2016-03-31 00:21:07 +00:00
|
|
|
LoadImages []string `mapstructure:"load"` // LoadImage is array of paths to image archive files
|
2017-01-22 22:04:41 +00:00
|
|
|
Command string `mapstructure:"command"` // The Command to run when the container starts up
|
|
|
|
Args []string `mapstructure:"args"` // The arguments to the Command
|
2016-01-08 22:34:49 +00:00
|
|
|
IpcMode string `mapstructure:"ipc_mode"` // The IPC mode of the container - host and none
|
2016-08-05 17:47:44 +00:00
|
|
|
NetworkMode string `mapstructure:"network_mode"` // The network mode of the container - host, nat and none
|
2016-11-11 16:38:16 +00:00
|
|
|
NetworkAliases []string `mapstructure:"network_aliases"` // The network-scoped alias for the container
|
2016-01-08 22:34:49 +00:00
|
|
|
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
|
2016-11-04 23:53:56 +00:00
|
|
|
UsernsMode string `mapstructure:"userns_mode"` // The User namespace mode of the container - host and none
|
2015-11-20 05:29:37 +00:00
|
|
|
PortMapRaw []map[string]int `mapstructure:"port_map"` //
|
|
|
|
PortMap map[string]int `mapstructure:"-"` // A map of host port labels and the ports exposed on the container
|
2016-05-15 16:41:34 +00:00
|
|
|
Privileged bool `mapstructure:"privileged"` // Flag to run the container in privileged mode
|
2015-11-18 05:41:00 +00:00
|
|
|
DNSServers []string `mapstructure:"dns_servers"` // DNS Server for containers
|
|
|
|
DNSSearchDomains []string `mapstructure:"dns_search_domains"` // DNS Search domains for containers
|
|
|
|
Hostname string `mapstructure:"hostname"` // Hostname for containers
|
2015-11-20 05:29:37 +00:00
|
|
|
LabelsRaw []map[string]string `mapstructure:"labels"` //
|
|
|
|
Labels map[string]string `mapstructure:"-"` // Labels to set when the container starts up
|
2015-11-18 18:31:06 +00:00
|
|
|
Auth []DockerDriverAuth `mapstructure:"auth"` // Authentication credentials for a private Docker registry
|
2016-04-08 17:51:07 +00:00
|
|
|
TTY bool `mapstructure:"tty"` // Allocate a Pseudo-TTY
|
|
|
|
Interactive bool `mapstructure:"interactive"` // Keep STDIN open even if not attached
|
2016-05-27 10:30:04 +00:00
|
|
|
ShmSize int64 `mapstructure:"shm_size"` // Size of /dev/shm of the container in bytes
|
2016-08-03 14:18:15 +00:00
|
|
|
WorkDir string `mapstructure:"work_dir"` // Working directory inside the container
|
2016-09-20 07:41:58 +00:00
|
|
|
Logging []DockerLoggingOpts `mapstructure:"logging"` // Logging options for syslog server
|
2016-09-20 09:22:27 +00:00
|
|
|
Volumes []string `mapstructure:"volumes"` // Host-Volumes to mount in, syntax: /path/to/host/directory:/destination/path/in/container
|
2017-01-09 21:55:01 +00:00
|
|
|
ForcePull bool `mapstructure:"force_pull"` // Always force pull before running image, useful if your tags are mutable
|
2015-11-14 02:09:42 +00:00
|
|
|
}
|
|
|
|
|
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")
|
|
|
|
}
|
2015-11-15 10:58:46 +00:00
|
|
|
|
2015-11-20 05:29:37 +00:00
|
|
|
c.PortMap = mapMergeStrInt(c.PortMapRaw...)
|
|
|
|
c.Labels = mapMergeStrStr(c.LabelsRaw...)
|
2016-09-27 20:13:55 +00:00
|
|
|
if len(c.Logging) > 0 {
|
2016-09-20 07:41:58 +00:00
|
|
|
c.Logging[0].Config = mapMergeStrStr(c.Logging[0].ConfigRaw...)
|
2016-09-20 09:22:27 +00:00
|
|
|
}
|
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
|
2016-11-08 22:18:40 +00:00
|
|
|
func NewDockerDriverConfig(task *structs.Task, env *env.TaskEnvironment) (*DockerDriverConfig, error) {
|
|
|
|
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
|
|
|
|
|
|
|
// Interpolate everthing that is a string
|
|
|
|
dconf.ImageName = env.ReplaceEnv(dconf.ImageName)
|
|
|
|
dconf.Command = env.ReplaceEnv(dconf.Command)
|
|
|
|
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)
|
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)
|
|
|
|
dconf.Volumes = env.ParseAndReplace(dconf.Volumes)
|
|
|
|
dconf.DNSServers = env.ParseAndReplace(dconf.DNSServers)
|
|
|
|
dconf.DNSSearchDomains = env.ParseAndReplace(dconf.DNSSearchDomains)
|
|
|
|
dconf.LoadImages = env.ParseAndReplace(dconf.LoadImages)
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, m := range dconf.PortMapRaw {
|
|
|
|
for k, v := range m {
|
|
|
|
delete(m, k)
|
|
|
|
m[env.ReplaceEnv(k)] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove any http
|
|
|
|
if strings.Contains(dconf.ImageName, "https://") {
|
|
|
|
dconf.ImageName = strings.Replace(dconf.ImageName, "https://", "", 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
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
|
|
|
|
containerID string
|
|
|
|
version string
|
2016-06-10 21:32:45 +00:00
|
|
|
clkSpeed float64
|
2016-05-25 19:36:37 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
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{
|
|
|
|
"image": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
|
|
|
Required: true,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"load": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"command": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"args": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"ipc_mode": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"network_mode": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-11-11 16:38:16 +00:00
|
|
|
"network_aliases": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"pid_mode": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"uts_mode": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-11-04 23:53:56 +00:00
|
|
|
"userns_mode": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"port_map": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"privileged": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"dns_servers": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"dns_search_domains": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"hostname": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"labels": &fields.FieldSchema{
|
2016-04-25 21:58:31 +00:00
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"auth": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"ssl": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-09 22:38:42 +00:00
|
|
|
"tty": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeBool,
|
2016-04-08 20:19:43 +00:00
|
|
|
},
|
2016-04-10 10:20:01 +00:00
|
|
|
"interactive": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeBool,
|
|
|
|
},
|
2016-05-27 10:30:04 +00:00
|
|
|
"shm_size": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeInt,
|
|
|
|
},
|
2016-08-03 14:18:15 +00:00
|
|
|
"work_dir": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeString,
|
|
|
|
},
|
2016-09-20 07:41:58 +00:00
|
|
|
"logging": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
},
|
2016-09-20 09:22:27 +00:00
|
|
|
"volumes": &fields.FieldSchema{
|
|
|
|
Type: fields.TypeArray,
|
|
|
|
},
|
2016-12-28 18:18:38 +00:00
|
|
|
"force_pull": &fields.FieldSchema{
|
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
func (d *DockerDriver) FSIsolation() cstructs.FSIsolation {
|
|
|
|
return cstructs.FSIsolationImage
|
|
|
|
}
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
func (d *DockerDriver) Prestart(ctx *ExecContext, task *structs.Task) (*CreatedResources, error) {
|
2016-11-08 22:18:40 +00:00
|
|
|
driverConfig, err := NewDockerDriverConfig(task, d.taskEnv)
|
|
|
|
if err != nil {
|
2017-01-10 21:24:45 +00:00
|
|
|
return nil, err
|
2016-11-08 22:18:40 +00:00
|
|
|
}
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
// Set state needed by Start()
|
|
|
|
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
|
2016-12-03 01:04:07 +00:00
|
|
|
if err := d.createImage(driverConfig, client, ctx.TaskDir); err != nil {
|
2017-01-10 21:24:45 +00:00
|
|
|
return nil, err
|
2016-11-08 22:18:40 +00:00
|
|
|
}
|
|
|
|
|
2017-01-13 01:21:54 +00:00
|
|
|
// Regardless of whether the image was downloaded already or not, store
|
|
|
|
// it as a created resource. Cleanup will soft fail if the image is
|
|
|
|
// still in use by another contianer.
|
|
|
|
dockerImage, err := client.InspectImage(driverConfig.ImageName)
|
2016-11-08 22:18:40 +00:00
|
|
|
if err != nil {
|
2017-01-13 01:21:54 +00:00
|
|
|
d.logger.Printf("[ERR] driver.docker: failed getting image id for %q: %v", driverConfig.ImageName, err)
|
2017-01-18 00:04:09 +00:00
|
|
|
return nil, err
|
2016-11-08 22:18:40 +00:00
|
|
|
}
|
|
|
|
|
2017-01-13 01:21:54 +00:00
|
|
|
res := NewCreatedResources()
|
|
|
|
res.Add(dockerImageResKey, dockerImage.ID)
|
2016-11-30 00:39:36 +00:00
|
|
|
d.imageID = dockerImage.ID
|
2017-01-13 01:21:54 +00:00
|
|
|
return res, nil
|
2016-11-30 00:39:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *DockerDriver) Start(ctx *ExecContext, task *structs.Task) (DriverHandle, 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{
|
|
|
|
TaskEnv: d.taskEnv,
|
|
|
|
Task: task,
|
|
|
|
Driver: "docker",
|
|
|
|
AllocID: ctx.AllocID,
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only launch syslog server if we're going to use it!
|
|
|
|
syslogAddr := ""
|
2016-11-30 00:39:36 +00:00
|
|
|
if runtime.GOOS == "darwin" && len(d.driverConfig.Logging) == 0 {
|
2016-11-08 22:18:40 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: disabling syslog driver as Docker for Mac workaround")
|
2016-11-30 00:39:36 +00:00
|
|
|
} else if len(d.driverConfig.Logging) == 0 || d.driverConfig.Logging[0].Type == "syslog" {
|
2016-11-08 22:18:40 +00:00
|
|
|
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-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
|
|
|
}
|
|
|
|
|
2017-01-14 00:46:08 +00:00
|
|
|
container, err := d.createContainer(config)
|
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed to create container: %s", err)
|
2016-11-08 22:18:40 +00:00
|
|
|
pluginClient.Kill()
|
2017-01-14 00:46:08 +00:00
|
|
|
if rerr, ok := err.(*structs.RecoverableError); ok {
|
|
|
|
rerr.Err = fmt.Sprintf("Failed to create container: %s", rerr.Err)
|
|
|
|
return nil, rerr
|
|
|
|
}
|
|
|
|
return nil, 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()
|
2016-11-30 00:39:36 +00:00
|
|
|
return nil, fmt.Errorf("Failed to start container %s: %s", container.ID, err)
|
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,
|
|
|
|
containerID: container.ID,
|
|
|
|
version: d.config.Version,
|
|
|
|
killTimeout: GetKillTimeout(task.KillTimeout, maxKill),
|
|
|
|
maxKillTimeout: maxKill,
|
|
|
|
doneCh: make(chan bool),
|
|
|
|
waitCh: make(chan *dstructs.WaitResult, 1),
|
|
|
|
}
|
|
|
|
if err := exec.SyncServices(consulContext(d.config, container.ID)); err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: error registering services with consul for task: %q: %v", task.Name, err)
|
|
|
|
}
|
|
|
|
go h.collectStats()
|
|
|
|
go h.run()
|
|
|
|
return h, nil
|
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
func (d *DockerDriver) cleanupImage(id string) error {
|
|
|
|
if !d.config.ReadBoolDefault(dockerCleanupImageConfigOption, dockerCleanupImageConfigDefault) {
|
|
|
|
// Config says not to cleanup
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := client.RemoveImage(id); err != nil {
|
|
|
|
if err == docker.ErrNoSuchImage {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: unable to cleanup image %q: does not exist", id)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if derr, ok := err.(*docker.Error); ok && derr.Status == 409 {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: unable to cleanup image %q: still in use", id)
|
|
|
|
return nil
|
2017-01-10 21:24:45 +00:00
|
|
|
}
|
2017-01-14 00:46:08 +00:00
|
|
|
// Retry on unknown errors
|
|
|
|
return structs.NewRecoverableError(err, true)
|
2017-01-10 21:24:45 +00:00
|
|
|
}
|
2017-01-13 01:21:54 +00:00
|
|
|
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: cleanup removed downloaded image: %q", id)
|
|
|
|
return nil
|
2017-01-10 21:24:45 +00:00
|
|
|
}
|
|
|
|
|
2016-06-11 18:34:41 +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) {
|
|
|
|
if client != nil && waitClient != nil {
|
|
|
|
return client, waitClient, nil
|
2015-10-07 00:53:05 +00:00
|
|
|
}
|
|
|
|
|
2015-12-10 21:49:29 +00:00
|
|
|
var err error
|
2016-06-11 18:34:41 +00:00
|
|
|
var merr multierror.Error
|
|
|
|
createClients.Do(func() {
|
2016-06-17 20:23:30 +00:00
|
|
|
if err = shelpers.Init(); err != nil {
|
|
|
|
d.logger.Printf("[FATAL] driver.docker: unable to initialize stats: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-12-10 21:49:29 +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)
|
|
|
|
client, err = docker.NewTLSClient(dockerEndpoint, cert, key, ca)
|
2016-06-21 23:25:10 +00:00
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
|
|
|
waitClient, err = docker.NewTLSClient(dockerEndpoint, cert, key, ca)
|
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
2015-12-10 21:49:29 +00:00
|
|
|
} else {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: using standard client connection to %s", dockerEndpoint)
|
|
|
|
client, err = docker.NewClient(dockerEndpoint)
|
2016-06-21 23:25:10 +00:00
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
|
|
|
waitClient, err = docker.NewClient(dockerEndpoint)
|
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
2015-12-10 21:49:29 +00:00
|
|
|
}
|
2016-06-21 23:25:10 +00:00
|
|
|
client.SetTimeout(dockerTimeout)
|
2015-12-10 21:49:29 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
d.logger.Println("[DEBUG] driver.docker: using client connection initialized from environment")
|
|
|
|
client, err = docker.NewClientFromEnv()
|
2016-06-11 18:34:41 +00:00
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
2016-06-21 23:25:10 +00:00
|
|
|
client.SetTimeout(dockerTimeout)
|
2016-06-11 18:34:41 +00:00
|
|
|
|
|
|
|
waitClient, err = docker.NewClientFromEnv()
|
|
|
|
if err != nil {
|
|
|
|
merr.Errors = append(merr.Errors, err)
|
|
|
|
}
|
2015-12-10 21:49:29 +00:00
|
|
|
})
|
2016-06-11 18:34:41 +00:00
|
|
|
return client, waitClient, merr.ErrorOrNil()
|
2015-10-06 23:26:31 +00:00
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
|
2016-04-01 09:22:17 +00:00
|
|
|
// Get the current status so that we can log any debug messages only if the
|
|
|
|
// state changes
|
|
|
|
_, currentlyEnabled := node.Attributes[dockerDriverAttr]
|
|
|
|
|
2016-06-11 18:34:41 +00:00
|
|
|
// Initialize docker API clients
|
|
|
|
client, _, err := d.dockerClients()
|
2015-09-03 10:38:36 +00:00
|
|
|
if err != nil {
|
2016-04-01 01:11:27 +00:00
|
|
|
delete(node.Attributes, dockerDriverAttr)
|
2016-04-01 09:22:17 +00:00
|
|
|
if currentlyEnabled {
|
|
|
|
d.logger.Printf("[INFO] driver.docker: failed to initialize client: %s", err)
|
|
|
|
}
|
2015-09-03 10:38:36 +00:00
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2016-09-27 20:13:55 +00:00
|
|
|
privileged := d.config.ReadBoolDefault(dockerPrivilegedConfigOption, false)
|
2015-11-18 00:58:23 +00:00
|
|
|
if privileged {
|
2016-09-27 20:13:55 +00:00
|
|
|
node.Attributes[dockerPrivilegedConfigOption] = "1"
|
2015-09-27 01:53:15 +00:00
|
|
|
}
|
|
|
|
|
2015-11-11 00:18:52 +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.
|
2015-09-26 06:13:40 +00:00
|
|
|
env, err := client.Version()
|
2015-09-26 06:55:01 +00:00
|
|
|
if err != nil {
|
2016-04-01 09:22:17 +00:00
|
|
|
if currentlyEnabled {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: could not connect to docker daemon at %s: %s", client.Endpoint(), err)
|
|
|
|
}
|
2016-04-01 01:11:27 +00:00
|
|
|
delete(node.Attributes, dockerDriverAttr)
|
2015-11-11 00:18:52 +00:00
|
|
|
return false, nil
|
2015-09-26 06:13:40 +00:00
|
|
|
}
|
2016-04-01 09:22:17 +00:00
|
|
|
|
2016-04-01 01:11:27 +00:00
|
|
|
node.Attributes[dockerDriverAttr] = "1"
|
2015-09-26 06:55:01 +00:00
|
|
|
node.Attributes["driver.docker.version"] = env.Get("Version")
|
2016-09-27 20:13:55 +00:00
|
|
|
|
2016-10-24 23:00:19 +00:00
|
|
|
// Advertise if this node supports Docker volumes
|
2016-10-20 00:13:45 +00:00
|
|
|
if d.config.ReadBoolDefault(dockerVolumesConfigOption, dockerVolumesConfigDefault) {
|
2016-09-27 20:13:55 +00:00
|
|
|
node.Attributes["driver."+dockerVolumesConfigOption] = "1"
|
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
func (d *DockerDriver) containerBinds(driverConfig *DockerDriverConfig, taskDir *allocdir.TaskDir,
|
2016-09-27 20:13:55 +00:00
|
|
|
task *structs.Task) ([]string, error) {
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
allocDirBind := fmt.Sprintf("%s:%s", taskDir.SharedAllocDir, allocdir.SharedAllocContainerPath)
|
|
|
|
taskLocalBind := fmt.Sprintf("%s:%s", taskDir.LocalDir, allocdir.TaskLocalContainerPath)
|
|
|
|
secretDirBind := fmt.Sprintf("%s:%s", taskDir.SecretsDir, allocdir.TaskSecretsContainerPath)
|
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
|
|
|
|
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
|
|
|
|
// Expand path relative to alloc dir
|
2016-12-03 01:04:07 +00:00
|
|
|
parts[0] = filepath.Join(taskDir.Dir, parts[0])
|
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
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
binds, err := d.containerBinds(driverConfig, ctx.TaskDir, task)
|
2015-10-15 23:40:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return c, err
|
|
|
|
}
|
|
|
|
|
2015-11-13 01:23:04 +00:00
|
|
|
config := &docker.Config{
|
2017-01-14 00:53:58 +00:00
|
|
|
Image: d.imageID,
|
2016-04-08 17:51:07 +00:00
|
|
|
Hostname: driverConfig.Hostname,
|
|
|
|
User: task.User,
|
|
|
|
Tty: driverConfig.TTY,
|
|
|
|
OpenStdin: driverConfig.Interactive,
|
2015-11-13 01:23:04 +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
|
|
|
|
2016-09-27 20:13:55 +00:00
|
|
|
if len(driverConfig.Logging) == 0 {
|
2016-10-26 00:27:13 +00:00
|
|
|
if runtime.GOOS != "darwin" {
|
|
|
|
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-10-27 19:31:53 +00:00
|
|
|
} else {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: deferring logging to docker on Docker for Mac")
|
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.
|
2016-07-28 19:17:00 +00:00
|
|
|
Memory: memLimit,
|
|
|
|
MemorySwap: memLimit, // MemorySwap is memory + swap.
|
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,
|
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)
|
|
|
|
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
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// set DNS search domains
|
2015-11-18 05:41:00 +00:00
|
|
|
for _, domain := range driverConfig.DNSSearchDomains {
|
|
|
|
hostConfig.DNSSearch = append(hostConfig.DNSSearch, domain)
|
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
|
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
|
|
|
}
|
|
|
|
|
2016-01-24 09:31:03 +00:00
|
|
|
d.taskEnv.SetPortMap(driverConfig.PortMap)
|
|
|
|
|
2015-11-13 01:23:04 +00:00
|
|
|
hostConfig.PortBindings = publishedPorts
|
|
|
|
config.ExposedPorts = exposedPorts
|
2015-09-26 01:22:10 +00:00
|
|
|
}
|
|
|
|
|
2016-01-22 23:00:36 +00:00
|
|
|
d.taskEnv.Build()
|
|
|
|
parsedArgs := d.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
|
|
|
}
|
|
|
|
|
2016-01-22 23:00:36 +00:00
|
|
|
config.Env = d.taskEnv.EnvList()
|
2015-11-18 04:04:10 +00:00
|
|
|
|
|
|
|
containerName := fmt.Sprintf("%s-%s", task.Name, ctx.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
|
2016-11-11 16:38:16 +00:00
|
|
|
if len(driverConfig.NetworkAliases) > 0 {
|
2016-12-19 22:22:08 +00:00
|
|
|
networkingConfig = &docker.NetworkingConfig{
|
|
|
|
EndpointsConfig: map[string]*docker.EndpointConfig{
|
|
|
|
hostConfig.NetworkMode: &docker.EndpointConfig{
|
|
|
|
Aliases: driverConfig.NetworkAliases,
|
|
|
|
},
|
|
|
|
},
|
2016-11-11 16:38:16 +00:00
|
|
|
}
|
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
|
|
|
}
|
|
|
|
|
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-02-29 00:56:05 +00:00
|
|
|
var (
|
|
|
|
// imageNotFoundMatcher is a regex expression that matches the image not
|
|
|
|
// found error Docker returns.
|
|
|
|
imageNotFoundMatcher = regexp.MustCompile(`Error: image .+ not found`)
|
|
|
|
)
|
|
|
|
|
|
|
|
// recoverablePullError wraps the error gotten when trying to pull and image if
|
|
|
|
// the error is recoverable.
|
|
|
|
func (d *DockerDriver) recoverablePullError(err error, image string) error {
|
|
|
|
recoverable := true
|
|
|
|
if imageNotFoundMatcher.MatchString(err.Error()) {
|
|
|
|
recoverable = false
|
|
|
|
}
|
2016-10-23 01:08:30 +00:00
|
|
|
return structs.NewRecoverableError(fmt.Errorf("Failed to pull `%s`: %s", image, err), recoverable)
|
2016-02-29 00:56:05 +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
|
2016-12-03 01:04:07 +00:00
|
|
|
func (d *DockerDriver) createImage(driverConfig *DockerDriverConfig, client *docker.Client, taskDir *allocdir.TaskDir) error {
|
2015-11-14 02:09:42 +00:00
|
|
|
image := driverConfig.ImageName
|
2015-09-26 01:22:10 +00:00
|
|
|
repo, tag := docker.ParseRepositoryTag(image)
|
|
|
|
if tag == "" {
|
|
|
|
tag = "latest"
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 {
|
|
|
|
d.logger.Printf("[DEBUG] driver.docker: force pull image '%s:%s' instead of inspecting local", repo, tag)
|
|
|
|
} else if tag != "latest" {
|
2017-01-10 21:24:45 +00:00
|
|
|
if dockerImage, _ := client.InspectImage(image); dockerImage != nil {
|
|
|
|
// Image exists, nothing to do
|
2017-01-13 01:21:54 +00:00
|
|
|
return 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
|
|
|
|
if len(driverConfig.LoadImages) > 0 {
|
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
|
|
|
|
if err := d.pullImage(driverConfig, client, repo, tag); err != nil {
|
2017-01-13 01:21:54 +00:00
|
|
|
return err
|
2016-03-30 20:09:32 +00:00
|
|
|
}
|
2017-01-13 01:21:54 +00:00
|
|
|
return nil
|
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
|
2016-03-30 20:09:32 +00:00
|
|
|
func (d *DockerDriver) pullImage(driverConfig *DockerDriverConfig, client *docker.Client, repo string, tag string) error {
|
|
|
|
pullOptions := docker.PullImageOptions{
|
|
|
|
Repository: repo,
|
|
|
|
Tag: tag,
|
|
|
|
}
|
|
|
|
|
|
|
|
authOptions := docker.AuthConfiguration{}
|
|
|
|
if len(driverConfig.Auth) != 0 {
|
|
|
|
authOptions = docker.AuthConfiguration{
|
|
|
|
Username: driverConfig.Auth[0].Username,
|
|
|
|
Password: driverConfig.Auth[0].Password,
|
|
|
|
Email: driverConfig.Auth[0].Email,
|
|
|
|
ServerAddress: driverConfig.Auth[0].ServerAddress,
|
2015-11-05 18:47:41 +00:00
|
|
|
}
|
2016-03-30 20:09:32 +00:00
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
if authConfigFile := d.config.Read("docker.auth.config"); authConfigFile != "" {
|
|
|
|
authOptionsPtr, err := authOptionFrom(authConfigFile, repo)
|
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[INFO] driver.docker: failed to find docker auth for repo %q: %v", repo, err)
|
|
|
|
return fmt.Errorf("Failed to find docker auth for repo %q: %v", repo, err)
|
2015-09-26 01:22:10 +00:00
|
|
|
}
|
2017-01-12 19:22:35 +00:00
|
|
|
|
|
|
|
authOptions = *authOptionsPtr
|
2015-09-03 10:38:36 +00:00
|
|
|
}
|
2016-02-10 02:24:30 +00:00
|
|
|
|
2016-12-20 19:57:26 +00:00
|
|
|
d.emitEvent("Downloading image %s:%s", repo, tag)
|
2016-03-30 20:09:32 +00:00
|
|
|
err := client.PullImage(pullOptions, authOptions)
|
|
|
|
if err != nil {
|
|
|
|
d.logger.Printf("[ERR] driver.docker: failed pulling container %s:%s: %s", repo, tag, err)
|
|
|
|
return d.recoverablePullError(err, driverConfig.ImageName)
|
|
|
|
}
|
2017-01-10 21:24:45 +00:00
|
|
|
|
2016-03-30 20:09:32 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: docker pull %s:%s succeeded", repo, tag)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-03-30 22:26:51 +00:00
|
|
|
// loadImage creates an image by loading it from the file system
|
2016-12-03 01:04:07 +00:00
|
|
|
func (d *DockerDriver) loadImage(driverConfig *DockerDriverConfig, client *docker.Client, taskDir *allocdir.TaskDir) error {
|
2016-03-31 00:21:07 +00:00
|
|
|
var errors multierror.Error
|
|
|
|
for _, image := range driverConfig.LoadImages {
|
2016-12-03 01:04:07 +00:00
|
|
|
archive := filepath.Join(taskDir.LocalDir, image)
|
2016-03-31 00:21:07 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: loading image from: %v", archive)
|
|
|
|
f, err := os.Open(archive)
|
|
|
|
if err != nil {
|
|
|
|
errors.Errors = append(errors.Errors, fmt.Errorf("unable to open image archive: %v", err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err := client.LoadImage(docker.LoadImageOptions{InputStream: f}); err != nil {
|
|
|
|
errors.Errors = append(errors.Errors, err)
|
|
|
|
}
|
|
|
|
f.Close()
|
2016-03-30 20:09:32 +00:00
|
|
|
}
|
2016-03-31 00:21:07 +00:00
|
|
|
return errors.ErrorOrNil()
|
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.
|
2017-01-14 00:46:08 +00:00
|
|
|
func (d *DockerDriver) createContainer(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)
|
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)
|
2016-11-04 21:39:56 +00:00
|
|
|
for _, container := range containers {
|
2016-11-29 22:29:37 +00:00
|
|
|
d.logger.Printf("[DEBUG] driver.docker: listed container %+v", container)
|
2016-11-04 21:39:56 +00:00
|
|
|
found := false
|
|
|
|
for _, name := range container.Names {
|
2016-11-29 01:37:22 +00:00
|
|
|
if name == containerName {
|
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
|
|
|
|
container, err := client.InspectContainer(container.ID)
|
|
|
|
if err != nil {
|
2016-11-30 23:59:47 +00:00
|
|
|
return nil, recoverableErrTimeouts(fmt.Errorf("Failed to inspect container %s: %s", container.ID, err))
|
2016-11-30 00:29:30 +00:00
|
|
|
}
|
|
|
|
if container != nil && (container.State.Running || container.State.FinishedAt.IsZero()) {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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{
|
|
|
|
"id": []string{pid.ContainerID},
|
|
|
|
},
|
|
|
|
})
|
2015-09-04 04:00:16 +00:00
|
|
|
if err != nil {
|
2015-09-26 06:13:40 +00:00
|
|
|
return nil, fmt.Errorf("Failed to query for container %s: %v", pid.ContainerID, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
found := false
|
|
|
|
for _, container := range containers {
|
|
|
|
if container.ID == pid.ContainerID {
|
|
|
|
found = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !found {
|
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
|
|
|
|
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,
|
|
|
|
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-03-24 22:39:10 +00:00
|
|
|
if err := exec.SyncServices(consulContext(d.config, pid.ContainerID)); err != nil {
|
|
|
|
h.logger.Printf("[ERR] driver.docker: error registering services with consul: %v", err)
|
|
|
|
}
|
|
|
|
|
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,
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
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")
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
h.logger.Printf("[DEBUG] driver.docker: attempted to stop non-existent container %s", h.containerID)
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2015-09-03 10:38:36 +00:00
|
|
|
close(h.doneCh)
|
2016-02-10 02:24:30 +00:00
|
|
|
|
2016-03-23 19:59:22 +00:00
|
|
|
// Remove services
|
|
|
|
if err := h.executor.DeregisterServices(); err != nil {
|
|
|
|
h.logger.Printf("[ERR] driver.docker: error deregistering services: %v", err)
|
|
|
|
}
|
|
|
|
|
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
|
|
|
cores := len(s.CPUStats.CPUUsage.PercpuUsage)
|
|
|
|
cs.Percent = calculatePercent(
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage,
|
|
|
|
s.CPUStats.SystemCPUUsage, s.PreCPUStats.SystemCPUUsage, cores)
|
|
|
|
cs.SystemMode = calculatePercent(
|
|
|
|
s.CPUStats.CPUUsage.UsageInKernelmode, s.PreCPUStats.CPUUsage.UsageInKernelmode,
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, cores)
|
|
|
|
cs.UserMode = calculatePercent(
|
|
|
|
s.CPUStats.CPUUsage.UsageInUsermode, s.PreCPUStats.CPUUsage.UsageInUsermode,
|
|
|
|
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, cores)
|
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
|
|
|
|
|
|
|
// authOptionsFrom takes the Docker auth config file and the repo being pulled
|
|
|
|
// and returns an AuthConfiguration or an error if the file/repo could not be
|
|
|
|
// parsed or looked up.
|
|
|
|
func authOptionFrom(file, repo string) (*docker.AuthConfiguration, error) {
|
|
|
|
name, err := reference.ParseNamed(repo)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to parse named repo %q: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
repoInfo, err := registry.ParseRepositoryInfo(name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to parse repository: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
f, err := os.Open(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to open auth config file: %v, error: %v", file, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
cfile := new(configfile.ConfigFile)
|
|
|
|
if err := cfile.LoadFromReader(f); err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to parse auth config file: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
dockerAuthConfig := registry.ResolveAuthConfig(cfile.AuthConfigs, repoInfo.Index)
|
|
|
|
|
|
|
|
// Convert to Api version
|
|
|
|
apiAuthConfig := &docker.AuthConfiguration{
|
|
|
|
Username: dockerAuthConfig.Username,
|
|
|
|
Password: dockerAuthConfig.Password,
|
|
|
|
Email: dockerAuthConfig.Email,
|
|
|
|
ServerAddress: dockerAuthConfig.ServerAddress,
|
|
|
|
}
|
|
|
|
|
|
|
|
return apiAuthConfig, nil
|
|
|
|
}
|