github.com/simonswine/terraform@v0.9.0-beta2/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("dns"); ok { 130 hostConfig.DNS = stringSetToStringSlice(v.(*schema.Set)) 131 } 132 133 if v, ok := d.GetOk("dns_opts"); ok { 134 hostConfig.DNSOptions = stringSetToStringSlice(v.(*schema.Set)) 135 } 136 137 if v, ok := d.GetOk("dns_search"); ok { 138 hostConfig.DNSSearch = stringSetToStringSlice(v.(*schema.Set)) 139 } 140 141 if v, ok := d.GetOk("links"); ok { 142 hostConfig.Links = stringSetToStringSlice(v.(*schema.Set)) 143 } 144 145 if v, ok := d.GetOk("memory"); ok { 146 hostConfig.Memory = int64(v.(int)) * 1024 * 1024 147 } 148 149 if v, ok := d.GetOk("memory_swap"); ok { 150 swap := int64(v.(int)) 151 if swap > 0 { 152 swap = swap * 1024 * 1024 153 } 154 hostConfig.MemorySwap = swap 155 } 156 157 if v, ok := d.GetOk("cpu_shares"); ok { 158 hostConfig.CPUShares = int64(v.(int)) 159 } 160 161 if v, ok := d.GetOk("log_opts"); ok { 162 hostConfig.LogConfig.Config = mapTypeMapValsToString(v.(map[string]interface{})) 163 } 164 165 if v, ok := d.GetOk("network_mode"); ok { 166 hostConfig.NetworkMode = v.(string) 167 } 168 169 createOpts.HostConfig = hostConfig 170 171 var retContainer *dc.Container 172 if retContainer, err = client.CreateContainer(createOpts); err != nil { 173 return fmt.Errorf("Unable to create container: %s", err) 174 } 175 if retContainer == nil { 176 return fmt.Errorf("Returned container is nil") 177 } 178 179 d.SetId(retContainer.ID) 180 181 if v, ok := d.GetOk("networks"); ok { 182 connectionOpts := dc.NetworkConnectionOptions{Container: retContainer.ID} 183 184 for _, rawNetwork := range v.(*schema.Set).List() { 185 network := rawNetwork.(string) 186 if err := client.ConnectNetwork(network, connectionOpts); err != nil { 187 return fmt.Errorf("Unable to connect to network '%s': %s", network, err) 188 } 189 } 190 } 191 192 if v, ok := d.GetOk("upload"); ok { 193 for _, upload := range v.(*schema.Set).List() { 194 content := upload.(map[string]interface{})["content"].(string) 195 file := upload.(map[string]interface{})["file"].(string) 196 197 buf := new(bytes.Buffer) 198 tw := tar.NewWriter(buf) 199 hdr := &tar.Header{ 200 Name: file, 201 Mode: 0644, 202 Size: int64(len(content)), 203 } 204 if err := tw.WriteHeader(hdr); err != nil { 205 return fmt.Errorf("Error creating tar archive: %s", err) 206 } 207 if _, err := tw.Write([]byte(content)); err != nil { 208 return fmt.Errorf("Error creating tar archive: %s", err) 209 } 210 if err := tw.Close(); err != nil { 211 return fmt.Errorf("Error creating tar archive: %s", err) 212 } 213 214 uploadOpts := dc.UploadToContainerOptions{ 215 InputStream: bytes.NewReader(buf.Bytes()), 216 Path: "/", 217 } 218 219 if err := client.UploadToContainer(retContainer.ID, uploadOpts); err != nil { 220 return fmt.Errorf("Unable to upload volume content: %s", err) 221 } 222 } 223 } 224 225 creationTime = time.Now() 226 if err := client.StartContainer(retContainer.ID, nil); err != nil { 227 return fmt.Errorf("Unable to start container: %s", err) 228 } 229 230 return resourceDockerContainerRead(d, meta) 231 } 232 233 func resourceDockerContainerRead(d *schema.ResourceData, meta interface{}) error { 234 client := meta.(*dc.Client) 235 236 apiContainer, err := fetchDockerContainer(d.Id(), client) 237 if err != nil { 238 return err 239 } 240 if apiContainer == nil { 241 // This container doesn't exist anymore 242 d.SetId("") 243 return nil 244 } 245 246 var container *dc.Container 247 248 loops := 1 // if it hasn't just been created, don't delay 249 if !creationTime.IsZero() { 250 loops = 30 // with 500ms spacing, 15 seconds; ought to be plenty 251 } 252 sleepTime := 500 * time.Millisecond 253 254 for i := loops; i > 0; i-- { 255 container, err = client.InspectContainer(apiContainer.ID) 256 if err != nil { 257 return fmt.Errorf("Error inspecting container %s: %s", apiContainer.ID, err) 258 } 259 260 if container.State.Running || 261 !container.State.Running && !d.Get("must_run").(bool) { 262 break 263 } 264 265 if creationTime.IsZero() { // We didn't just create it, so don't wait around 266 return resourceDockerContainerDelete(d, meta) 267 } 268 269 if container.State.FinishedAt.After(creationTime) { 270 // It exited immediately, so error out so dependent containers 271 // aren't started 272 resourceDockerContainerDelete(d, meta) 273 return fmt.Errorf("Container %s exited after creation, error was: %s", apiContainer.ID, container.State.Error) 274 } 275 276 time.Sleep(sleepTime) 277 } 278 279 // Handle the case of the for loop above running its course 280 if !container.State.Running && d.Get("must_run").(bool) { 281 resourceDockerContainerDelete(d, meta) 282 return fmt.Errorf("Container %s failed to be in running state", apiContainer.ID) 283 } 284 285 // Read Network Settings 286 if container.NetworkSettings != nil { 287 d.Set("ip_address", container.NetworkSettings.IPAddress) 288 d.Set("ip_prefix_length", container.NetworkSettings.IPPrefixLen) 289 d.Set("gateway", container.NetworkSettings.Gateway) 290 d.Set("bridge", container.NetworkSettings.Bridge) 291 } 292 293 return nil 294 } 295 296 func resourceDockerContainerUpdate(d *schema.ResourceData, meta interface{}) error { 297 return nil 298 } 299 300 func resourceDockerContainerDelete(d *schema.ResourceData, meta interface{}) error { 301 client := meta.(*dc.Client) 302 303 // Stop the container before removing if destroy_grace_seconds is defined 304 if d.Get("destroy_grace_seconds").(int) > 0 { 305 var timeout = uint(d.Get("destroy_grace_seconds").(int)) 306 if err := client.StopContainer(d.Id(), timeout); err != nil { 307 return fmt.Errorf("Error stopping container %s: %s", d.Id(), err) 308 } 309 } 310 311 removeOpts := dc.RemoveContainerOptions{ 312 ID: d.Id(), 313 RemoveVolumes: true, 314 Force: true, 315 } 316 317 if err := client.RemoveContainer(removeOpts); err != nil { 318 return fmt.Errorf("Error deleting container %s: %s", d.Id(), err) 319 } 320 321 d.SetId("") 322 return nil 323 } 324 325 func stringListToStringSlice(stringList []interface{}) []string { 326 ret := []string{} 327 for _, v := range stringList { 328 if v == nil { 329 ret = append(ret, "") 330 continue 331 } 332 ret = append(ret, v.(string)) 333 } 334 return ret 335 } 336 337 func stringSetToStringSlice(stringSet *schema.Set) []string { 338 ret := []string{} 339 if stringSet == nil { 340 return ret 341 } 342 for _, envVal := range stringSet.List() { 343 ret = append(ret, envVal.(string)) 344 } 345 return ret 346 } 347 348 func mapTypeMapValsToString(typeMap map[string]interface{}) map[string]string { 349 mapped := make(map[string]string, len(typeMap)) 350 for k, v := range typeMap { 351 mapped[k] = v.(string) 352 } 353 return mapped 354 } 355 356 func fetchDockerContainer(ID string, client *dc.Client) (*dc.APIContainers, error) { 357 apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true}) 358 359 if err != nil { 360 return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err) 361 } 362 363 for _, apiContainer := range apiContainers { 364 if apiContainer.ID == ID { 365 return &apiContainer, nil 366 } 367 } 368 369 return nil, nil 370 } 371 372 func portSetToDockerPorts(ports *schema.Set) (map[dc.Port]struct{}, map[dc.Port][]dc.PortBinding) { 373 retExposedPorts := map[dc.Port]struct{}{} 374 retPortBindings := map[dc.Port][]dc.PortBinding{} 375 376 for _, portInt := range ports.List() { 377 port := portInt.(map[string]interface{}) 378 internal := port["internal"].(int) 379 protocol := port["protocol"].(string) 380 381 exposedPort := dc.Port(strconv.Itoa(internal) + "/" + protocol) 382 retExposedPorts[exposedPort] = struct{}{} 383 384 external, extOk := port["external"].(int) 385 ip, ipOk := port["ip"].(string) 386 387 if extOk { 388 portBinding := dc.PortBinding{ 389 HostPort: strconv.Itoa(external), 390 } 391 if ipOk { 392 portBinding.HostIP = ip 393 } 394 retPortBindings[exposedPort] = append(retPortBindings[exposedPort], portBinding) 395 } 396 } 397 398 return retExposedPorts, retPortBindings 399 } 400 401 func extraHostsSetToDockerExtraHosts(extraHosts *schema.Set) []string { 402 retExtraHosts := []string{} 403 404 for _, hostInt := range extraHosts.List() { 405 host := hostInt.(map[string]interface{}) 406 ip := host["ip"].(string) 407 hostname := host["host"].(string) 408 retExtraHosts = append(retExtraHosts, hostname+":"+ip) 409 } 410 411 return retExtraHosts 412 } 413 414 func volumeSetToDockerVolumes(volumes *schema.Set) (map[string]struct{}, []string, []string, error) { 415 retVolumeMap := map[string]struct{}{} 416 retHostConfigBinds := []string{} 417 retVolumeFromContainers := []string{} 418 419 for _, volumeInt := range volumes.List() { 420 volume := volumeInt.(map[string]interface{}) 421 fromContainer := volume["from_container"].(string) 422 containerPath := volume["container_path"].(string) 423 volumeName := volume["volume_name"].(string) 424 if len(volumeName) == 0 { 425 volumeName = volume["host_path"].(string) 426 } 427 readOnly := volume["read_only"].(bool) 428 429 switch { 430 case len(fromContainer) == 0 && len(containerPath) == 0: 431 return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Volume entry without container path or source container") 432 case len(fromContainer) != 0 && len(containerPath) != 0: 433 return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Both a container and a path specified in a volume entry") 434 case len(fromContainer) != 0: 435 retVolumeFromContainers = append(retVolumeFromContainers, fromContainer) 436 case len(volumeName) != 0: 437 readWrite := "rw" 438 if readOnly { 439 readWrite = "ro" 440 } 441 retVolumeMap[containerPath] = struct{}{} 442 retHostConfigBinds = append(retHostConfigBinds, volumeName+":"+containerPath+":"+readWrite) 443 default: 444 retVolumeMap[containerPath] = struct{}{} 445 } 446 } 447 448 return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, nil 449 }