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