github.com/huiliang/nomad@v0.2.1-0.20151124023127-7a8b664699ff/client/driver/docker.go (about)

     1  package driver
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"log"
     7  	"net"
     8  	"path/filepath"
     9  	"strconv"
    10  	"strings"
    11  
    12  	docker "github.com/fsouza/go-dockerclient"
    13  
    14  	"github.com/hashicorp/nomad/client/allocdir"
    15  	"github.com/hashicorp/nomad/client/config"
    16  	"github.com/hashicorp/nomad/client/driver/args"
    17  	cstructs "github.com/hashicorp/nomad/client/driver/structs"
    18  	"github.com/hashicorp/nomad/client/fingerprint"
    19  	"github.com/hashicorp/nomad/nomad/structs"
    20  	"github.com/mitchellh/mapstructure"
    21  )
    22  
    23  type DockerDriver struct {
    24  	DriverContext
    25  	fingerprint.StaticFingerprinter
    26  }
    27  
    28  type DockerDriverAuth struct {
    29  	Username      string `mapstructure:"username"`       // username for the registry
    30  	Password      string `mapstructure:"password"`       // password to access the registry
    31  	Email         string `mapstructure:"email"`          // email address of the user who is allowed to access the registry
    32  	ServerAddress string `mapstructure:"server_address"` // server address of the registry
    33  }
    34  
    35  type DockerDriverConfig struct {
    36  	ImageName        string              `mapstructure:"image"`              // Container's Image Name
    37  	Command          string              `mapstructure:"command"`            // The Command/Entrypoint to run when the container starts up
    38  	Args             []string            `mapstructure:"args"`               // The arguments to the Command/Entrypoint
    39  	NetworkMode      string              `mapstructure:"network_mode"`       // The network mode of the container - host, net and none
    40  	PortMapRaw       []map[string]int    `mapstructure:"port_map"`           //
    41  	PortMap          map[string]int      `mapstructure:"-"`                  // A map of host port labels and the ports exposed on the container
    42  	Privileged       bool                `mapstructure:"privileged"`         // Flag to run the container in priviledged mode
    43  	DNSServers       []string            `mapstructure:"dns_servers"`        // DNS Server for containers
    44  	DNSSearchDomains []string            `mapstructure:"dns_search_domains"` // DNS Search domains for containers
    45  	Hostname         string              `mapstructure:"hostname"`           // Hostname for containers
    46  	LabelsRaw        []map[string]string `mapstructure:"labels"`             //
    47  	Labels           map[string]string   `mapstructure:"-"`                  // Labels to set when the container starts up
    48  	Auth             []DockerDriverAuth  `mapstructure:"auth"`               // Authentication credentials for a private Docker registry
    49  }
    50  
    51  func (c *DockerDriverConfig) Validate() error {
    52  	if c.ImageName == "" {
    53  		return fmt.Errorf("Docker Driver needs an image name")
    54  	}
    55  
    56  	c.PortMap = mapMergeStrInt(c.PortMapRaw...)
    57  	c.Labels = mapMergeStrStr(c.LabelsRaw...)
    58  
    59  	return nil
    60  }
    61  
    62  type dockerPID struct {
    63  	ImageID     string
    64  	ContainerID string
    65  }
    66  
    67  type DockerHandle struct {
    68  	client           *docker.Client
    69  	logger           *log.Logger
    70  	cleanupContainer bool
    71  	cleanupImage     bool
    72  	imageID          string
    73  	containerID      string
    74  	waitCh           chan *cstructs.WaitResult
    75  	doneCh           chan struct{}
    76  }
    77  
    78  func NewDockerDriver(ctx *DriverContext) Driver {
    79  	return &DockerDriver{DriverContext: *ctx}
    80  }
    81  
    82  // dockerClient creates *docker.Client. In test / dev mode we can use ENV vars
    83  // to connect to the docker daemon. In production mode we will read
    84  // docker.endpoint from the config file.
    85  func (d *DockerDriver) dockerClient() (*docker.Client, error) {
    86  	// Default to using whatever is configured in docker.endpoint. If this is
    87  	// not specified we'll fall back on NewClientFromEnv which reads config from
    88  	// the DOCKER_* environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and
    89  	// DOCKER_CERT_PATH. This allows us to lock down the config in production
    90  	// but also accept the standard ENV configs for dev and test.
    91  	dockerEndpoint := d.config.Read("docker.endpoint")
    92  	if dockerEndpoint != "" {
    93  		cert := d.config.Read("docker.tls.cert")
    94  		key := d.config.Read("docker.tls.key")
    95  		ca := d.config.Read("docker.tls.ca")
    96  
    97  		if cert+key+ca != "" {
    98  			d.logger.Printf("[DEBUG] driver.docker: using TLS client connection to %s", dockerEndpoint)
    99  			return docker.NewTLSClient(dockerEndpoint, cert, key, ca)
   100  		} else {
   101  			d.logger.Printf("[DEBUG] driver.docker: using standard client connection to %s", dockerEndpoint)
   102  			return docker.NewClient(dockerEndpoint)
   103  		}
   104  	}
   105  
   106  	d.logger.Println("[DEBUG] driver.docker: using client connection initialized from environment")
   107  	return docker.NewClientFromEnv()
   108  }
   109  
   110  func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
   111  	// Initialize docker API client
   112  	client, err := d.dockerClient()
   113  	if err != nil {
   114  		d.logger.Printf("[INFO] driver.docker: failed to initialize client: %s", err)
   115  		return false, nil
   116  	}
   117  
   118  	privileged := d.config.ReadBoolDefault("docker.privileged.enabled", false)
   119  	if privileged {
   120  		d.logger.Println("[INFO] driver.docker: privileged containers are enabled")
   121  		node.Attributes["docker.privileged.enabled"] = "1"
   122  	} else {
   123  		d.logger.Println("[INFO] driver.docker: privileged containers are disabled")
   124  	}
   125  
   126  	// This is the first operation taken on the client so we'll try to
   127  	// establish a connection to the Docker daemon. If this fails it means
   128  	// Docker isn't available so we'll simply disable the docker driver.
   129  	env, err := client.Version()
   130  	if err != nil {
   131  		d.logger.Printf("[INFO] driver.docker: could not connect to docker daemon at %s: %s", client.Endpoint(), err)
   132  		return false, nil
   133  	}
   134  	node.Attributes["driver.docker"] = "1"
   135  	node.Attributes["driver.docker.version"] = env.Get("Version")
   136  
   137  	return true, nil
   138  }
   139  
   140  func (d *DockerDriver) containerBinds(alloc *allocdir.AllocDir, task *structs.Task) ([]string, error) {
   141  	shared := alloc.SharedDir
   142  	local, ok := alloc.TaskDirs[task.Name]
   143  	if !ok {
   144  		return nil, fmt.Errorf("Failed to find task local directory: %v", task.Name)
   145  	}
   146  
   147  	return []string{
   148  		// "z" and "Z" option is to allocate directory with SELinux label.
   149  		fmt.Sprintf("%s:/%s:rw,z", shared, allocdir.SharedAllocName),
   150  		// capital "Z" will label with Multi-Category Security (MCS) labels
   151  		fmt.Sprintf("%s:/%s:rw,Z", local, allocdir.TaskLocal),
   152  	}, nil
   153  }
   154  
   155  // createContainer initializes a struct needed to call docker.client.CreateContainer()
   156  func (d *DockerDriver) createContainer(ctx *ExecContext, task *structs.Task, driverConfig *DockerDriverConfig) (docker.CreateContainerOptions, error) {
   157  	var c docker.CreateContainerOptions
   158  	if task.Resources == nil {
   159  		// Guard against missing resources. We should never have been able to
   160  		// schedule a job without specifying this.
   161  		d.logger.Println("[ERR] driver.docker: task.Resources is empty")
   162  		return c, fmt.Errorf("task.Resources is empty")
   163  	}
   164  
   165  	binds, err := d.containerBinds(ctx.AllocDir, task)
   166  	if err != nil {
   167  		return c, err
   168  	}
   169  
   170  	// Create environment variables.
   171  	env := TaskEnvironmentVariables(ctx, task)
   172  	env.SetAllocDir(filepath.Join("/", allocdir.SharedAllocName))
   173  	env.SetTaskLocalDir(filepath.Join("/", allocdir.TaskLocal))
   174  
   175  	config := &docker.Config{
   176  		Image:    driverConfig.ImageName,
   177  		Hostname: driverConfig.Hostname,
   178  	}
   179  
   180  	hostConfig := &docker.HostConfig{
   181  		// Convert MB to bytes. This is an absolute value.
   182  		//
   183  		// This value represents the total amount of memory a process can use.
   184  		// Swap is added to total memory and is managed by the OS, not docker.
   185  		// Since this may cause other processes to swap and cause system
   186  		// instability, we will simply not use swap.
   187  		//
   188  		// See: https://www.kernel.org/doc/Documentation/cgroups/memory.txt
   189  		Memory:     int64(task.Resources.MemoryMB) * 1024 * 1024,
   190  		MemorySwap: -1,
   191  		// Convert Mhz to shares. This is a relative value.
   192  		//
   193  		// There are two types of CPU limiters available: Shares and Quotas. A
   194  		// Share allows a particular process to have a proportion of CPU time
   195  		// relative to other processes; 1024 by default. A CPU Quota is enforced
   196  		// over a Period of time and is a HARD limit on the amount of CPU time a
   197  		// process can use. Processes with quotas cannot burst, while processes
   198  		// with shares can, so we'll use shares.
   199  		//
   200  		// The simplest scale is 1 share to 1 MHz so 1024 = 1GHz. This means any
   201  		// given process will have at least that amount of resources, but likely
   202  		// more since it is (probably) rare that the machine will run at 100%
   203  		// CPU. This scale will cease to work if a node is overprovisioned.
   204  		//
   205  		// See:
   206  		//  - https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
   207  		//  - https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt
   208  		CPUShares: int64(task.Resources.CPU),
   209  
   210  		// Binds are used to mount a host volume into the container. We mount a
   211  		// local directory for storage and a shared alloc directory that can be
   212  		// used to share data between different tasks in the same task group.
   213  		Binds: binds,
   214  	}
   215  
   216  	d.logger.Printf("[DEBUG] driver.docker: using %d bytes memory for %s", hostConfig.Memory, task.Config["image"])
   217  	d.logger.Printf("[DEBUG] driver.docker: using %d cpu shares for %s", hostConfig.CPUShares, task.Config["image"])
   218  	d.logger.Printf("[DEBUG] driver.docker: binding directories %#v for %s", hostConfig.Binds, task.Config["image"])
   219  
   220  	//  set privileged mode
   221  	hostPrivileged := d.config.ReadBoolDefault("docker.privileged.enabled", false)
   222  	if driverConfig.Privileged && !hostPrivileged {
   223  		return c, fmt.Errorf(`Docker privileged mode is disabled on this Nomad agent`)
   224  	}
   225  	hostConfig.Privileged = hostPrivileged
   226  
   227  	// set DNS servers
   228  	for _, ip := range driverConfig.DNSServers {
   229  		if net.ParseIP(ip) != nil {
   230  			hostConfig.DNS = append(hostConfig.DNS, ip)
   231  		} else {
   232  			d.logger.Printf("[ERR] driver.docker: invalid ip address for container dns server: %s", ip)
   233  		}
   234  	}
   235  
   236  	// set DNS search domains
   237  	for _, domain := range driverConfig.DNSSearchDomains {
   238  		hostConfig.DNSSearch = append(hostConfig.DNSSearch, domain)
   239  	}
   240  
   241  	hostConfig.NetworkMode = driverConfig.NetworkMode
   242  	if hostConfig.NetworkMode == "" {
   243  		// docker default
   244  		d.logger.Println("[DEBUG] driver.docker: networking mode not specified; defaulting to bridge")
   245  		hostConfig.NetworkMode = "bridge"
   246  	}
   247  
   248  	// Setup port mapping and exposed ports
   249  	if len(task.Resources.Networks) == 0 {
   250  		d.logger.Println("[DEBUG] driver.docker: No network interfaces are available")
   251  		if len(driverConfig.PortMap) > 0 {
   252  			return c, fmt.Errorf("Trying to map ports but no network interface is available")
   253  		}
   254  	} else {
   255  		// TODO add support for more than one network
   256  		network := task.Resources.Networks[0]
   257  		publishedPorts := map[docker.Port][]docker.PortBinding{}
   258  		exposedPorts := map[docker.Port]struct{}{}
   259  
   260  		for _, port := range network.ReservedPorts {
   261  			// By default we will map the allocated port 1:1 to the container
   262  			containerPortInt := port.Value
   263  
   264  			// If the user has mapped a port using port_map we'll change it here
   265  			if mapped, ok := driverConfig.PortMap[port.Label]; ok {
   266  				containerPortInt = mapped
   267  			}
   268  
   269  			hostPortStr := strconv.Itoa(port.Value)
   270  			containerPort := docker.Port(strconv.Itoa(containerPortInt))
   271  
   272  			publishedPorts[containerPort+"/tcp"] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: hostPortStr}}
   273  			publishedPorts[containerPort+"/udp"] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: hostPortStr}}
   274  			d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (static)", network.IP, port.Value, port.Value)
   275  
   276  			exposedPorts[containerPort+"/tcp"] = struct{}{}
   277  			exposedPorts[containerPort+"/udp"] = struct{}{}
   278  			d.logger.Printf("[DEBUG] driver.docker: exposed port %d", port.Value)
   279  		}
   280  
   281  		for _, port := range network.DynamicPorts {
   282  			// By default we will map the allocated port 1:1 to the container
   283  			containerPortInt := port.Value
   284  
   285  			// If the user has mapped a port using port_map we'll change it here
   286  			if mapped, ok := driverConfig.PortMap[port.Label]; ok {
   287  				containerPortInt = mapped
   288  			}
   289  
   290  			hostPortStr := strconv.Itoa(port.Value)
   291  			containerPort := docker.Port(strconv.Itoa(containerPortInt))
   292  
   293  			publishedPorts[containerPort+"/tcp"] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: hostPortStr}}
   294  			publishedPorts[containerPort+"/udp"] = []docker.PortBinding{docker.PortBinding{HostIP: network.IP, HostPort: hostPortStr}}
   295  			d.logger.Printf("[DEBUG] driver.docker: allocated port %s:%d -> %d (mapped)", network.IP, port.Value, containerPortInt)
   296  
   297  			exposedPorts[containerPort+"/tcp"] = struct{}{}
   298  			exposedPorts[containerPort+"/udp"] = struct{}{}
   299  			d.logger.Printf("[DEBUG] driver.docker: exposed port %s", containerPort)
   300  		}
   301  
   302  		// This was set above in a call to TaskEnvironmentVariables but if we
   303  		// have mapped any ports we will need to override them.
   304  		//
   305  		// TODO refactor the implementation in TaskEnvironmentVariables to match
   306  		// the 0.2 ports world view. Docker seems to be the only place where
   307  		// this is actually needed, but this is kinda hacky.
   308  		if len(driverConfig.PortMap) > 0 {
   309  			env.SetPorts(network.MapLabelToValues(driverConfig.PortMap))
   310  		}
   311  		hostConfig.PortBindings = publishedPorts
   312  		config.ExposedPorts = exposedPorts
   313  	}
   314  
   315  	parsedArgs := args.ParseAndReplace(driverConfig.Args, env.Map())
   316  
   317  	// If the user specified a custom command to run as their entrypoint, we'll
   318  	// inject it here.
   319  	if driverConfig.Command != "" {
   320  		cmd := []string{driverConfig.Command}
   321  		if len(driverConfig.Args) != 0 {
   322  			cmd = append(cmd, parsedArgs...)
   323  		}
   324  		d.logger.Printf("[DEBUG] driver.docker: setting container startup command to: %s", strings.Join(cmd, " "))
   325  		config.Cmd = cmd
   326  	} else if len(driverConfig.Args) != 0 {
   327  		d.logger.Println("[DEBUG] driver.docker: ignoring command arguments because command is not specified")
   328  	}
   329  
   330  	if len(driverConfig.Labels) > 0 {
   331  		config.Labels = driverConfig.Labels
   332  		d.logger.Printf("[DEBUG] driver.docker: applied labels on the container: %+v", config.Labels)
   333  	}
   334  
   335  	config.Env = env.List()
   336  
   337  	containerName := fmt.Sprintf("%s-%s", task.Name, ctx.AllocID)
   338  	d.logger.Printf("[DEBUG] driver.docker: setting container name to: %s", containerName)
   339  
   340  	return docker.CreateContainerOptions{
   341  		Name:       containerName,
   342  		Config:     config,
   343  		HostConfig: hostConfig,
   344  	}, nil
   345  }
   346  
   347  func (d *DockerDriver) Start(ctx *ExecContext, task *structs.Task) (DriverHandle, error) {
   348  	var driverConfig DockerDriverConfig
   349  	if err := mapstructure.WeakDecode(task.Config, &driverConfig); err != nil {
   350  		return nil, err
   351  	}
   352  	image := driverConfig.ImageName
   353  
   354  	if err := driverConfig.Validate(); err != nil {
   355  		return nil, err
   356  	}
   357  	if task.Resources == nil {
   358  		return nil, fmt.Errorf("Resources are not specified")
   359  	}
   360  	if task.Resources.MemoryMB == 0 {
   361  		return nil, fmt.Errorf("Memory limit cannot be zero")
   362  	}
   363  	if task.Resources.CPU == 0 {
   364  		return nil, fmt.Errorf("CPU limit cannot be zero")
   365  	}
   366  
   367  	cleanupContainer := d.config.ReadBoolDefault("docker.cleanup.container", true)
   368  	cleanupImage := d.config.ReadBoolDefault("docker.cleanup.image", true)
   369  
   370  	// Initialize docker API client
   371  	client, err := d.dockerClient()
   372  	if err != nil {
   373  		return nil, fmt.Errorf("Failed to connect to docker daemon: %s", err)
   374  	}
   375  
   376  	repo, tag := docker.ParseRepositoryTag(image)
   377  	// Make sure tag is always explicitly set. We'll default to "latest" if it
   378  	// isn't, which is the expected behavior.
   379  	if tag == "" {
   380  		tag = "latest"
   381  	}
   382  
   383  	var dockerImage *docker.Image
   384  	// We're going to check whether the image is already downloaded. If the tag
   385  	// is "latest" we have to check for a new version every time so we don't
   386  	// bother to check and cache the id here. We'll download first, then cache.
   387  	if tag != "latest" {
   388  		dockerImage, err = client.InspectImage(image)
   389  	}
   390  
   391  	// Download the image
   392  	if dockerImage == nil {
   393  		pullOptions := docker.PullImageOptions{
   394  			Repository: repo,
   395  			Tag:        tag,
   396  		}
   397  
   398  		authOptions := docker.AuthConfiguration{}
   399  		if len(driverConfig.Auth) != 0 {
   400  			authOptions = docker.AuthConfiguration{
   401  				Username:      driverConfig.Auth[0].Username,
   402  				Password:      driverConfig.Auth[0].Password,
   403  				Email:         driverConfig.Auth[0].Email,
   404  				ServerAddress: driverConfig.Auth[0].ServerAddress,
   405  			}
   406  		}
   407  
   408  		err = client.PullImage(pullOptions, authOptions)
   409  		if err != nil {
   410  			d.logger.Printf("[ERR] driver.docker: failed pulling container %s:%s: %s", repo, tag, err)
   411  			return nil, fmt.Errorf("Failed to pull `%s`: %s", image, err)
   412  		}
   413  		d.logger.Printf("[DEBUG] driver.docker: docker pull %s:%s succeeded", repo, tag)
   414  
   415  		// Now that we have the image we can get the image id
   416  		dockerImage, err = client.InspectImage(image)
   417  		if err != nil {
   418  			d.logger.Printf("[ERR] driver.docker: failed getting image id for %s: %s", image, err)
   419  			return nil, fmt.Errorf("Failed to determine image id for `%s`: %s", image, err)
   420  		}
   421  	}
   422  	d.logger.Printf("[DEBUG] driver.docker: identified image %s as %s", image, dockerImage.ID)
   423  
   424  	config, err := d.createContainer(ctx, task, &driverConfig)
   425  	if err != nil {
   426  		d.logger.Printf("[ERR] driver.docker: failed to create container configuration for image %s: %s", image, err)
   427  		return nil, fmt.Errorf("Failed to create container configuration for image %s: %s", image, err)
   428  	}
   429  	// Create a container
   430  	container, err := client.CreateContainer(config)
   431  	if err != nil {
   432  		// If the container already exists because of a previous failure we'll
   433  		// try to purge it and re-create it.
   434  		if strings.Contains(err.Error(), "container already exists") {
   435  			// Get the ID of the existing container so we can delete it
   436  			containers, err := client.ListContainers(docker.ListContainersOptions{
   437  				// The image might be in use by a stopped container, so check everything
   438  				All: true,
   439  				Filters: map[string][]string{
   440  					"name": []string{config.Name},
   441  				},
   442  			})
   443  			if err != nil {
   444  				log.Printf("[ERR] driver.docker: failed to query list of containers matching name:%s", config.Name)
   445  				return nil, fmt.Errorf("Failed to query list of containers: %s", err)
   446  			}
   447  
   448  			if len(containers) != 1 {
   449  				log.Printf("[ERR] driver.docker: failed to get id for container %s", config.Name)
   450  				return nil, fmt.Errorf("Failed to get id for container %s", config.Name)
   451  			}
   452  
   453  			log.Printf("[INFO] driver.docker: a container with the name %s already exists; will attempt to purge and re-create", config.Name)
   454  			err = client.RemoveContainer(docker.RemoveContainerOptions{
   455  				ID: containers[0].ID,
   456  			})
   457  			if err != nil {
   458  				log.Printf("[ERR] driver.docker: failed to purge container %s", config.Name)
   459  				return nil, fmt.Errorf("Failed to purge container %s: %s", config.Name, err)
   460  			}
   461  			log.Printf("[INFO] driver.docker: purged container %s", config.Name)
   462  			container, err = client.CreateContainer(config)
   463  			if err != nil {
   464  				log.Printf("[ERR] driver.docker: failed to re-create container %s; aborting", config.Name)
   465  				return nil, fmt.Errorf("Failed to re-create container %s; aborting", config.Name)
   466  			}
   467  		} else {
   468  			// We failed to create the container for some other reason.
   469  			d.logger.Printf("[ERR] driver.docker: failed to create container from image %s: %s", image, err)
   470  			return nil, fmt.Errorf("Failed to create container from image %s: %s", image, err)
   471  		}
   472  	}
   473  	d.logger.Printf("[INFO] driver.docker: created container %s", container.ID)
   474  
   475  	// Start the container
   476  	err = client.StartContainer(container.ID, container.HostConfig)
   477  	if err != nil {
   478  		d.logger.Printf("[ERR] driver.docker: failed to start container %s: %s", container.ID, err)
   479  		return nil, fmt.Errorf("Failed to start container %s: %s", container.ID, err)
   480  	}
   481  	d.logger.Printf("[INFO] driver.docker: started container %s", container.ID)
   482  
   483  	// Return a driver handle
   484  	h := &DockerHandle{
   485  		client:           client,
   486  		cleanupContainer: cleanupContainer,
   487  		cleanupImage:     cleanupImage,
   488  		logger:           d.logger,
   489  		imageID:          dockerImage.ID,
   490  		containerID:      container.ID,
   491  		doneCh:           make(chan struct{}),
   492  		waitCh:           make(chan *cstructs.WaitResult, 1),
   493  	}
   494  	go h.run()
   495  	return h, nil
   496  }
   497  
   498  func (d *DockerDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
   499  	cleanupContainer := d.config.ReadBoolDefault("docker.cleanup.container", true)
   500  	cleanupImage := d.config.ReadBoolDefault("docker.cleanup.image", true)
   501  
   502  	// Split the handle
   503  	pidBytes := []byte(strings.TrimPrefix(handleID, "DOCKER:"))
   504  	pid := &dockerPID{}
   505  	if err := json.Unmarshal(pidBytes, pid); err != nil {
   506  		return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
   507  	}
   508  	d.logger.Printf("[INFO] driver.docker: re-attaching to docker process: %s", handleID)
   509  
   510  	// Initialize docker API client
   511  	client, err := d.dockerClient()
   512  	if err != nil {
   513  		return nil, fmt.Errorf("Failed to connect to docker daemon: %s", err)
   514  	}
   515  
   516  	// Look for a running container with this ID
   517  	containers, err := client.ListContainers(docker.ListContainersOptions{
   518  		Filters: map[string][]string{
   519  			"id": []string{pid.ContainerID},
   520  		},
   521  	})
   522  	if err != nil {
   523  		return nil, fmt.Errorf("Failed to query for container %s: %v", pid.ContainerID, err)
   524  	}
   525  
   526  	found := false
   527  	for _, container := range containers {
   528  		if container.ID == pid.ContainerID {
   529  			found = true
   530  		}
   531  	}
   532  	if !found {
   533  		return nil, fmt.Errorf("Failed to find container %s: %v", pid.ContainerID, err)
   534  	}
   535  
   536  	// Return a driver handle
   537  	h := &DockerHandle{
   538  		client:           client,
   539  		cleanupContainer: cleanupContainer,
   540  		cleanupImage:     cleanupImage,
   541  		logger:           d.logger,
   542  		imageID:          pid.ImageID,
   543  		containerID:      pid.ContainerID,
   544  		doneCh:           make(chan struct{}),
   545  		waitCh:           make(chan *cstructs.WaitResult, 1),
   546  	}
   547  	go h.run()
   548  	return h, nil
   549  }
   550  
   551  func (h *DockerHandle) ID() string {
   552  	// Return a handle to the PID
   553  	pid := dockerPID{
   554  		ImageID:     h.imageID,
   555  		ContainerID: h.containerID,
   556  	}
   557  	data, err := json.Marshal(pid)
   558  	if err != nil {
   559  		h.logger.Printf("[ERR] driver.docker: failed to marshal docker PID to JSON: %s", err)
   560  	}
   561  	return fmt.Sprintf("DOCKER:%s", string(data))
   562  }
   563  
   564  func (h *DockerHandle) ContainerID() string {
   565  	return h.containerID
   566  }
   567  
   568  func (h *DockerHandle) WaitCh() chan *cstructs.WaitResult {
   569  	return h.waitCh
   570  }
   571  
   572  func (h *DockerHandle) Update(task *structs.Task) error {
   573  	// Update is not possible
   574  	return nil
   575  }
   576  
   577  // Kill is used to terminate the task. This uses docker stop -t 5
   578  func (h *DockerHandle) Kill() error {
   579  	// Stop the container
   580  	err := h.client.StopContainer(h.containerID, 5)
   581  	if err != nil {
   582  		log.Printf("[ERR] driver.docker: failed to stop container %s", h.containerID)
   583  		return fmt.Errorf("Failed to stop container %s: %s", h.containerID, err)
   584  	}
   585  	log.Printf("[INFO] driver.docker: stopped container %s", h.containerID)
   586  
   587  	// Cleanup container
   588  	if h.cleanupContainer {
   589  		err = h.client.RemoveContainer(docker.RemoveContainerOptions{
   590  			ID:            h.containerID,
   591  			RemoveVolumes: true,
   592  		})
   593  		if err != nil {
   594  			log.Printf("[ERR] driver.docker: failed to remove container %s", h.containerID)
   595  			return fmt.Errorf("Failed to remove container %s: %s", h.containerID, err)
   596  		}
   597  		log.Printf("[INFO] driver.docker: removed container %s", h.containerID)
   598  	}
   599  
   600  	// Cleanup image. This operation may fail if the image is in use by another
   601  	// job. That is OK. Will we log a message but continue.
   602  	if h.cleanupImage {
   603  		err = h.client.RemoveImage(h.imageID)
   604  		if err != nil {
   605  			containers, err := h.client.ListContainers(docker.ListContainersOptions{
   606  				// The image might be in use by a stopped container, so check everything
   607  				All: true,
   608  				Filters: map[string][]string{
   609  					"image": []string{h.imageID},
   610  				},
   611  			})
   612  			if err != nil {
   613  				log.Printf("[ERR] driver.docker: failed to query list of containers matching image:%s", h.imageID)
   614  				return fmt.Errorf("Failed to query list of containers: %s", err)
   615  			}
   616  			inUse := len(containers)
   617  			if inUse > 0 {
   618  				log.Printf("[INFO] driver.docker: image %s is still in use by %d container(s)", h.imageID, inUse)
   619  			} else {
   620  				return fmt.Errorf("Failed to remove image %s", h.imageID)
   621  			}
   622  		} else {
   623  			log.Printf("[INFO] driver.docker: removed image %s", h.imageID)
   624  		}
   625  	}
   626  	return nil
   627  }
   628  
   629  func (h *DockerHandle) run() {
   630  	// Wait for it...
   631  	exitCode, err := h.client.WaitContainer(h.containerID)
   632  	if err != nil {
   633  		h.logger.Printf("[ERR] driver.docker: failed to wait for %s; container already terminated", h.containerID)
   634  	}
   635  
   636  	if exitCode != 0 {
   637  		err = fmt.Errorf("Docker container exited with non-zero exit code: %d", exitCode)
   638  	}
   639  
   640  	close(h.doneCh)
   641  	h.waitCh <- cstructs.NewWaitResult(exitCode, 0, err)
   642  	close(h.waitCh)
   643  }