github.com/danrjohnson/terraform@v0.7.0-rc2.0.20160627135212-d0fc1fa086ff/builtin/providers/docker/resource_docker_container_funcs.go (about)

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