github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/docker/resource_docker_container_funcs.go (about)

     1  package docker
     2  
     3  import (
     4  	"archive/tar"
     5  	"bytes"
     6  	"errors"
     7  	"fmt"
     8  	"strconv"
     9  	"time"
    10  
    11  	dc "github.com/fsouza/go-dockerclient"
    12  	"github.com/hashicorp/terraform/helper/schema"
    13  )
    14  
    15  var (
    16  	creationTime time.Time
    17  )
    18  
    19  func resourceDockerContainerCreate(d *schema.ResourceData, meta interface{}) error {
    20  	var err error
    21  	client := meta.(*dc.Client)
    22  
    23  	var data Data
    24  	if err := fetchLocalImages(&data, client); err != nil {
    25  		return err
    26  	}
    27  
    28  	image := d.Get("image").(string)
    29  	if _, ok := data.DockerImages[image]; !ok {
    30  		if _, ok := data.DockerImages[image+":latest"]; !ok {
    31  			return fmt.Errorf("Unable to find image %s", image)
    32  		}
    33  		image = image + ":latest"
    34  	}
    35  
    36  	// The awesome, wonderful, splendiferous, sensical
    37  	// Docker API now lets you specify a HostConfig in
    38  	// CreateContainerOptions, but in my testing it still only
    39  	// actually applies HostConfig options set in StartContainer.
    40  	// How cool is that?
    41  	createOpts := dc.CreateContainerOptions{
    42  		Name: d.Get("name").(string),
    43  		Config: &dc.Config{
    44  			Image:      image,
    45  			Hostname:   d.Get("hostname").(string),
    46  			Domainname: d.Get("domainname").(string),
    47  		},
    48  	}
    49  
    50  	if v, ok := d.GetOk("env"); ok {
    51  		createOpts.Config.Env = stringSetToStringSlice(v.(*schema.Set))
    52  	}
    53  
    54  	if v, ok := d.GetOk("command"); ok {
    55  		createOpts.Config.Cmd = stringListToStringSlice(v.([]interface{}))
    56  		for _, v := range createOpts.Config.Cmd {
    57  			if v == "" {
    58  				return fmt.Errorf("values for command may not be empty")
    59  			}
    60  		}
    61  	}
    62  
    63  	if v, ok := d.GetOk("entrypoint"); ok {
    64  		createOpts.Config.Entrypoint = stringListToStringSlice(v.([]interface{}))
    65  	}
    66  
    67  	if v, ok := d.GetOk("user"); ok {
    68  		createOpts.Config.User = v.(string)
    69  	}
    70  
    71  	exposedPorts := map[dc.Port]struct{}{}
    72  	portBindings := map[dc.Port][]dc.PortBinding{}
    73  
    74  	if v, ok := d.GetOk("ports"); ok {
    75  		exposedPorts, portBindings = portSetToDockerPorts(v.(*schema.Set))
    76  	}
    77  	if len(exposedPorts) != 0 {
    78  		createOpts.Config.ExposedPorts = exposedPorts
    79  	}
    80  
    81  	extraHosts := []string{}
    82  	if v, ok := d.GetOk("host"); ok {
    83  		extraHosts = extraHostsSetToDockerExtraHosts(v.(*schema.Set))
    84  	}
    85  
    86  	volumes := map[string]struct{}{}
    87  	binds := []string{}
    88  	volumesFrom := []string{}
    89  
    90  	if v, ok := d.GetOk("volumes"); ok {
    91  		volumes, binds, volumesFrom, err = volumeSetToDockerVolumes(v.(*schema.Set))
    92  		if err != nil {
    93  			return fmt.Errorf("Unable to parse volumes: %s", err)
    94  		}
    95  	}
    96  	if len(volumes) != 0 {
    97  		createOpts.Config.Volumes = volumes
    98  	}
    99  
   100  	if v, ok := d.GetOk("labels"); ok {
   101  		createOpts.Config.Labels = mapTypeMapValsToString(v.(map[string]interface{}))
   102  	}
   103  
   104  	hostConfig := &dc.HostConfig{
   105  		Privileged:      d.Get("privileged").(bool),
   106  		PublishAllPorts: d.Get("publish_all_ports").(bool),
   107  		RestartPolicy: dc.RestartPolicy{
   108  			Name:              d.Get("restart").(string),
   109  			MaximumRetryCount: d.Get("max_retry_count").(int),
   110  		},
   111  		LogConfig: dc.LogConfig{
   112  			Type: d.Get("log_driver").(string),
   113  		},
   114  	}
   115  
   116  	if len(portBindings) != 0 {
   117  		hostConfig.PortBindings = portBindings
   118  	}
   119  	if len(extraHosts) != 0 {
   120  		hostConfig.ExtraHosts = extraHosts
   121  	}
   122  	if len(binds) != 0 {
   123  		hostConfig.Binds = binds
   124  	}
   125  	if len(volumesFrom) != 0 {
   126  		hostConfig.VolumesFrom = volumesFrom
   127  	}
   128  
   129  	if v, ok := d.GetOk("capabilities"); ok {
   130  		for _, capInt := range v.(*schema.Set).List() {
   131  			capa := capInt.(map[string]interface{})
   132  			hostConfig.CapAdd = stringSetToStringSlice(capa["add"].(*schema.Set))
   133  			hostConfig.CapDrop = stringSetToStringSlice(capa["drop"].(*schema.Set))
   134  			break
   135  		}
   136  	}
   137  
   138  	if v, ok := d.GetOk("dns"); ok {
   139  		hostConfig.DNS = stringSetToStringSlice(v.(*schema.Set))
   140  	}
   141  
   142  	if v, ok := d.GetOk("dns_opts"); ok {
   143  		hostConfig.DNSOptions = stringSetToStringSlice(v.(*schema.Set))
   144  	}
   145  
   146  	if v, ok := d.GetOk("dns_search"); ok {
   147  		hostConfig.DNSSearch = stringSetToStringSlice(v.(*schema.Set))
   148  	}
   149  
   150  	if v, ok := d.GetOk("links"); ok {
   151  		hostConfig.Links = stringSetToStringSlice(v.(*schema.Set))
   152  	}
   153  
   154  	if v, ok := d.GetOk("memory"); ok {
   155  		hostConfig.Memory = int64(v.(int)) * 1024 * 1024
   156  	}
   157  
   158  	if v, ok := d.GetOk("memory_swap"); ok {
   159  		swap := int64(v.(int))
   160  		if swap > 0 {
   161  			swap = swap * 1024 * 1024
   162  		}
   163  		hostConfig.MemorySwap = swap
   164  	}
   165  
   166  	if v, ok := d.GetOk("cpu_shares"); ok {
   167  		hostConfig.CPUShares = int64(v.(int))
   168  	}
   169  
   170  	if v, ok := d.GetOk("log_opts"); ok {
   171  		hostConfig.LogConfig.Config = mapTypeMapValsToString(v.(map[string]interface{}))
   172  	}
   173  
   174  	if v, ok := d.GetOk("network_mode"); ok {
   175  		hostConfig.NetworkMode = v.(string)
   176  	}
   177  
   178  	createOpts.HostConfig = hostConfig
   179  
   180  	var retContainer *dc.Container
   181  	if retContainer, err = client.CreateContainer(createOpts); err != nil {
   182  		return fmt.Errorf("Unable to create container: %s", err)
   183  	}
   184  	if retContainer == nil {
   185  		return fmt.Errorf("Returned container is nil")
   186  	}
   187  
   188  	d.SetId(retContainer.ID)
   189  
   190  	if v, ok := d.GetOk("networks"); ok {
   191  		connectionOpts := dc.NetworkConnectionOptions{Container: retContainer.ID}
   192  
   193  		for _, rawNetwork := range v.(*schema.Set).List() {
   194  			network := rawNetwork.(string)
   195  			if err := client.ConnectNetwork(network, connectionOpts); err != nil {
   196  				return fmt.Errorf("Unable to connect to network '%s': %s", network, err)
   197  			}
   198  		}
   199  	}
   200  
   201  	if v, ok := d.GetOk("upload"); ok {
   202  		for _, upload := range v.(*schema.Set).List() {
   203  			content := upload.(map[string]interface{})["content"].(string)
   204  			file := upload.(map[string]interface{})["file"].(string)
   205  
   206  			buf := new(bytes.Buffer)
   207  			tw := tar.NewWriter(buf)
   208  			hdr := &tar.Header{
   209  				Name: file,
   210  				Mode: 0644,
   211  				Size: int64(len(content)),
   212  			}
   213  			if err := tw.WriteHeader(hdr); err != nil {
   214  				return fmt.Errorf("Error creating tar archive: %s", err)
   215  			}
   216  			if _, err := tw.Write([]byte(content)); err != nil {
   217  				return fmt.Errorf("Error creating tar archive: %s", err)
   218  			}
   219  			if err := tw.Close(); err != nil {
   220  				return fmt.Errorf("Error creating tar archive: %s", err)
   221  			}
   222  
   223  			uploadOpts := dc.UploadToContainerOptions{
   224  				InputStream: bytes.NewReader(buf.Bytes()),
   225  				Path:        "/",
   226  			}
   227  
   228  			if err := client.UploadToContainer(retContainer.ID, uploadOpts); err != nil {
   229  				return fmt.Errorf("Unable to upload volume content: %s", err)
   230  			}
   231  		}
   232  	}
   233  
   234  	creationTime = time.Now()
   235  	if err := client.StartContainer(retContainer.ID, nil); err != nil {
   236  		return fmt.Errorf("Unable to start container: %s", err)
   237  	}
   238  
   239  	return resourceDockerContainerRead(d, meta)
   240  }
   241  
   242  func resourceDockerContainerRead(d *schema.ResourceData, meta interface{}) error {
   243  	client := meta.(*dc.Client)
   244  
   245  	apiContainer, err := fetchDockerContainer(d.Id(), client)
   246  	if err != nil {
   247  		return err
   248  	}
   249  	if apiContainer == nil {
   250  		// This container doesn't exist anymore
   251  		d.SetId("")
   252  		return nil
   253  	}
   254  
   255  	var container *dc.Container
   256  
   257  	loops := 1 // if it hasn't just been created, don't delay
   258  	if !creationTime.IsZero() {
   259  		loops = 30 // with 500ms spacing, 15 seconds; ought to be plenty
   260  	}
   261  	sleepTime := 500 * time.Millisecond
   262  
   263  	for i := loops; i > 0; i-- {
   264  		container, err = client.InspectContainer(apiContainer.ID)
   265  		if err != nil {
   266  			return fmt.Errorf("Error inspecting container %s: %s", apiContainer.ID, err)
   267  		}
   268  
   269  		if container.State.Running ||
   270  			!container.State.Running && !d.Get("must_run").(bool) {
   271  			break
   272  		}
   273  
   274  		if creationTime.IsZero() { // We didn't just create it, so don't wait around
   275  			return resourceDockerContainerDelete(d, meta)
   276  		}
   277  
   278  		if container.State.FinishedAt.After(creationTime) {
   279  			// It exited immediately, so error out so dependent containers
   280  			// aren't started
   281  			resourceDockerContainerDelete(d, meta)
   282  			return fmt.Errorf("Container %s exited after creation, error was: %s", apiContainer.ID, container.State.Error)
   283  		}
   284  
   285  		time.Sleep(sleepTime)
   286  	}
   287  
   288  	// Handle the case of the for loop above running its course
   289  	if !container.State.Running && d.Get("must_run").(bool) {
   290  		resourceDockerContainerDelete(d, meta)
   291  		return fmt.Errorf("Container %s failed to be in running state", apiContainer.ID)
   292  	}
   293  
   294  	// Read Network Settings
   295  	if container.NetworkSettings != nil {
   296  		d.Set("ip_address", container.NetworkSettings.IPAddress)
   297  		d.Set("ip_prefix_length", container.NetworkSettings.IPPrefixLen)
   298  		d.Set("gateway", container.NetworkSettings.Gateway)
   299  		d.Set("bridge", container.NetworkSettings.Bridge)
   300  	}
   301  
   302  	return nil
   303  }
   304  
   305  func resourceDockerContainerUpdate(d *schema.ResourceData, meta interface{}) error {
   306  	return nil
   307  }
   308  
   309  func resourceDockerContainerDelete(d *schema.ResourceData, meta interface{}) error {
   310  	client := meta.(*dc.Client)
   311  
   312  	// Stop the container before removing if destroy_grace_seconds is defined
   313  	if d.Get("destroy_grace_seconds").(int) > 0 {
   314  		var timeout = uint(d.Get("destroy_grace_seconds").(int))
   315  		if err := client.StopContainer(d.Id(), timeout); err != nil {
   316  			return fmt.Errorf("Error stopping container %s: %s", d.Id(), err)
   317  		}
   318  	}
   319  
   320  	removeOpts := dc.RemoveContainerOptions{
   321  		ID:            d.Id(),
   322  		RemoveVolumes: true,
   323  		Force:         true,
   324  	}
   325  
   326  	if err := client.RemoveContainer(removeOpts); err != nil {
   327  		return fmt.Errorf("Error deleting container %s: %s", d.Id(), err)
   328  	}
   329  
   330  	d.SetId("")
   331  	return nil
   332  }
   333  
   334  func stringListToStringSlice(stringList []interface{}) []string {
   335  	ret := []string{}
   336  	for _, v := range stringList {
   337  		if v == nil {
   338  			ret = append(ret, "")
   339  			continue
   340  		}
   341  		ret = append(ret, v.(string))
   342  	}
   343  	return ret
   344  }
   345  
   346  func stringSetToStringSlice(stringSet *schema.Set) []string {
   347  	ret := []string{}
   348  	if stringSet == nil {
   349  		return ret
   350  	}
   351  	for _, envVal := range stringSet.List() {
   352  		ret = append(ret, envVal.(string))
   353  	}
   354  	return ret
   355  }
   356  
   357  func mapTypeMapValsToString(typeMap map[string]interface{}) map[string]string {
   358  	mapped := make(map[string]string, len(typeMap))
   359  	for k, v := range typeMap {
   360  		mapped[k] = v.(string)
   361  	}
   362  	return mapped
   363  }
   364  
   365  func fetchDockerContainer(ID string, client *dc.Client) (*dc.APIContainers, error) {
   366  	apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true})
   367  
   368  	if err != nil {
   369  		return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
   370  	}
   371  
   372  	for _, apiContainer := range apiContainers {
   373  		if apiContainer.ID == ID {
   374  			return &apiContainer, nil
   375  		}
   376  	}
   377  
   378  	return nil, nil
   379  }
   380  
   381  func portSetToDockerPorts(ports *schema.Set) (map[dc.Port]struct{}, map[dc.Port][]dc.PortBinding) {
   382  	retExposedPorts := map[dc.Port]struct{}{}
   383  	retPortBindings := map[dc.Port][]dc.PortBinding{}
   384  
   385  	for _, portInt := range ports.List() {
   386  		port := portInt.(map[string]interface{})
   387  		internal := port["internal"].(int)
   388  		protocol := port["protocol"].(string)
   389  
   390  		exposedPort := dc.Port(strconv.Itoa(internal) + "/" + protocol)
   391  		retExposedPorts[exposedPort] = struct{}{}
   392  
   393  		external, extOk := port["external"].(int)
   394  		ip, ipOk := port["ip"].(string)
   395  
   396  		if extOk {
   397  			portBinding := dc.PortBinding{
   398  				HostPort: strconv.Itoa(external),
   399  			}
   400  			if ipOk {
   401  				portBinding.HostIP = ip
   402  			}
   403  			retPortBindings[exposedPort] = append(retPortBindings[exposedPort], portBinding)
   404  		}
   405  	}
   406  
   407  	return retExposedPorts, retPortBindings
   408  }
   409  
   410  func extraHostsSetToDockerExtraHosts(extraHosts *schema.Set) []string {
   411  	retExtraHosts := []string{}
   412  
   413  	for _, hostInt := range extraHosts.List() {
   414  		host := hostInt.(map[string]interface{})
   415  		ip := host["ip"].(string)
   416  		hostname := host["host"].(string)
   417  		retExtraHosts = append(retExtraHosts, hostname+":"+ip)
   418  	}
   419  
   420  	return retExtraHosts
   421  }
   422  
   423  func volumeSetToDockerVolumes(volumes *schema.Set) (map[string]struct{}, []string, []string, error) {
   424  	retVolumeMap := map[string]struct{}{}
   425  	retHostConfigBinds := []string{}
   426  	retVolumeFromContainers := []string{}
   427  
   428  	for _, volumeInt := range volumes.List() {
   429  		volume := volumeInt.(map[string]interface{})
   430  		fromContainer := volume["from_container"].(string)
   431  		containerPath := volume["container_path"].(string)
   432  		volumeName := volume["volume_name"].(string)
   433  		if len(volumeName) == 0 {
   434  			volumeName = volume["host_path"].(string)
   435  		}
   436  		readOnly := volume["read_only"].(bool)
   437  
   438  		switch {
   439  		case len(fromContainer) == 0 && len(containerPath) == 0:
   440  			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Volume entry without container path or source container")
   441  		case len(fromContainer) != 0 && len(containerPath) != 0:
   442  			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Both a container and a path specified in a volume entry")
   443  		case len(fromContainer) != 0:
   444  			retVolumeFromContainers = append(retVolumeFromContainers, fromContainer)
   445  		case len(volumeName) != 0:
   446  			readWrite := "rw"
   447  			if readOnly {
   448  				readWrite = "ro"
   449  			}
   450  			retVolumeMap[containerPath] = struct{}{}
   451  			retHostConfigBinds = append(retHostConfigBinds, volumeName+":"+containerPath+":"+readWrite)
   452  		default:
   453  			retVolumeMap[containerPath] = struct{}{}
   454  		}
   455  	}
   456  
   457  	return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, nil
   458  }