github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/cluster/executor/container/container.go (about) 1 package container 2 3 import ( 4 "errors" 5 "fmt" 6 "net" 7 "strconv" 8 "strings" 9 "time" 10 11 "github.com/sirupsen/logrus" 12 13 "github.com/docker/distribution/reference" 14 "github.com/docker/docker/api/types" 15 enginecontainer "github.com/docker/docker/api/types/container" 16 "github.com/docker/docker/api/types/events" 17 "github.com/docker/docker/api/types/filters" 18 enginemount "github.com/docker/docker/api/types/mount" 19 "github.com/docker/docker/api/types/network" 20 volumetypes "github.com/docker/docker/api/types/volume" 21 "github.com/docker/docker/daemon/cluster/convert" 22 executorpkg "github.com/docker/docker/daemon/cluster/executor" 23 clustertypes "github.com/docker/docker/daemon/cluster/provider" 24 "github.com/docker/go-connections/nat" 25 netconst "github.com/docker/libnetwork/datastore" 26 "github.com/docker/swarmkit/agent/exec" 27 "github.com/docker/swarmkit/api" 28 "github.com/docker/swarmkit/api/genericresource" 29 "github.com/docker/swarmkit/template" 30 gogotypes "github.com/gogo/protobuf/types" 31 ) 32 33 const ( 34 // Explicitly use the kernel's default setting for CPU quota of 100ms. 35 // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt 36 cpuQuotaPeriod = 100 * time.Millisecond 37 38 // systemLabelPrefix represents the reserved namespace for system labels. 39 systemLabelPrefix = "com.docker.swarm" 40 ) 41 42 // containerConfig converts task properties into docker container compatible 43 // components. 44 type containerConfig struct { 45 task *api.Task 46 networksAttachments map[string]*api.NetworkAttachment 47 } 48 49 // newContainerConfig returns a validated container config. No methods should 50 // return an error if this function returns without error. 51 func newContainerConfig(t *api.Task, node *api.NodeDescription) (*containerConfig, error) { 52 var c containerConfig 53 return &c, c.setTask(t, node) 54 } 55 56 func (c *containerConfig) setTask(t *api.Task, node *api.NodeDescription) error { 57 if t.Spec.GetContainer() == nil && t.Spec.GetAttachment() == nil { 58 return exec.ErrRuntimeUnsupported 59 } 60 61 container := t.Spec.GetContainer() 62 if container != nil { 63 if container.Image == "" { 64 return ErrImageRequired 65 } 66 67 if err := validateMounts(container.Mounts); err != nil { 68 return err 69 } 70 } 71 72 // index the networks by name 73 c.networksAttachments = make(map[string]*api.NetworkAttachment, len(t.Networks)) 74 for _, attachment := range t.Networks { 75 c.networksAttachments[attachment.Network.Spec.Annotations.Name] = attachment 76 } 77 78 c.task = t 79 80 if t.Spec.GetContainer() != nil { 81 preparedSpec, err := template.ExpandContainerSpec(node, t) 82 if err != nil { 83 return err 84 } 85 c.task.Spec.Runtime = &api.TaskSpec_Container{ 86 Container: preparedSpec, 87 } 88 } 89 90 return nil 91 } 92 93 func (c *containerConfig) networkAttachmentContainerID() string { 94 attachment := c.task.Spec.GetAttachment() 95 if attachment == nil { 96 return "" 97 } 98 99 return attachment.ContainerID 100 } 101 102 func (c *containerConfig) taskID() string { 103 return c.task.ID 104 } 105 106 func (c *containerConfig) endpoint() *api.Endpoint { 107 return c.task.Endpoint 108 } 109 110 func (c *containerConfig) spec() *api.ContainerSpec { 111 return c.task.Spec.GetContainer() 112 } 113 114 func (c *containerConfig) nameOrID() string { 115 if c.task.Spec.GetContainer() != nil { 116 return c.name() 117 } 118 119 return c.networkAttachmentContainerID() 120 } 121 122 func (c *containerConfig) name() string { 123 if c.task.Annotations.Name != "" { 124 // if set, use the container Annotations.Name field, set in the orchestrator. 125 return c.task.Annotations.Name 126 } 127 128 slot := fmt.Sprint(c.task.Slot) 129 if slot == "" || c.task.Slot == 0 { 130 slot = c.task.NodeID 131 } 132 133 // fallback to service.slot.id. 134 return fmt.Sprintf("%s.%s.%s", c.task.ServiceAnnotations.Name, slot, c.task.ID) 135 } 136 137 func (c *containerConfig) image() string { 138 raw := c.spec().Image 139 ref, err := reference.ParseNormalizedNamed(raw) 140 if err != nil { 141 return raw 142 } 143 return reference.FamiliarString(reference.TagNameOnly(ref)) 144 } 145 146 func (c *containerConfig) portBindings() nat.PortMap { 147 portBindings := nat.PortMap{} 148 if c.task.Endpoint == nil { 149 return portBindings 150 } 151 152 for _, portConfig := range c.task.Endpoint.Ports { 153 if portConfig.PublishMode != api.PublishModeHost { 154 continue 155 } 156 157 port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String()))) 158 binding := []nat.PortBinding{ 159 {}, 160 } 161 162 if portConfig.PublishedPort != 0 { 163 binding[0].HostPort = strconv.Itoa(int(portConfig.PublishedPort)) 164 } 165 portBindings[port] = binding 166 } 167 168 return portBindings 169 } 170 171 func (c *containerConfig) isolation() enginecontainer.Isolation { 172 return convert.IsolationFromGRPC(c.spec().Isolation) 173 } 174 175 func (c *containerConfig) exposedPorts() map[nat.Port]struct{} { 176 exposedPorts := make(map[nat.Port]struct{}) 177 if c.task.Endpoint == nil { 178 return exposedPorts 179 } 180 181 for _, portConfig := range c.task.Endpoint.Ports { 182 if portConfig.PublishMode != api.PublishModeHost { 183 continue 184 } 185 186 port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String()))) 187 exposedPorts[port] = struct{}{} 188 } 189 190 return exposedPorts 191 } 192 193 func (c *containerConfig) config() *enginecontainer.Config { 194 genericEnvs := genericresource.EnvFormat(c.task.AssignedGenericResources, "DOCKER_RESOURCE") 195 env := append(c.spec().Env, genericEnvs...) 196 197 config := &enginecontainer.Config{ 198 Labels: c.labels(), 199 StopSignal: c.spec().StopSignal, 200 Tty: c.spec().TTY, 201 OpenStdin: c.spec().OpenStdin, 202 User: c.spec().User, 203 Env: env, 204 Hostname: c.spec().Hostname, 205 WorkingDir: c.spec().Dir, 206 Image: c.image(), 207 ExposedPorts: c.exposedPorts(), 208 Healthcheck: c.healthcheck(), 209 } 210 211 if len(c.spec().Command) > 0 { 212 // If Command is provided, we replace the whole invocation with Command 213 // by replacing Entrypoint and specifying Cmd. Args is ignored in this 214 // case. 215 config.Entrypoint = append(config.Entrypoint, c.spec().Command...) 216 config.Cmd = append(config.Cmd, c.spec().Args...) 217 } else if len(c.spec().Args) > 0 { 218 // In this case, we assume the image has an Entrypoint and Args 219 // specifies the arguments for that entrypoint. 220 config.Cmd = c.spec().Args 221 } 222 223 return config 224 } 225 226 func (c *containerConfig) labels() map[string]string { 227 var ( 228 system = map[string]string{ 229 "task": "", // mark as cluster task 230 "task.id": c.task.ID, 231 "task.name": c.name(), 232 "node.id": c.task.NodeID, 233 "service.id": c.task.ServiceID, 234 "service.name": c.task.ServiceAnnotations.Name, 235 } 236 labels = make(map[string]string) 237 ) 238 239 // base labels are those defined in the spec. 240 for k, v := range c.spec().Labels { 241 labels[k] = v 242 } 243 244 // we then apply the overrides from the task, which may be set via the 245 // orchestrator. 246 for k, v := range c.task.Annotations.Labels { 247 labels[k] = v 248 } 249 250 // finally, we apply the system labels, which override all labels. 251 for k, v := range system { 252 labels[strings.Join([]string{systemLabelPrefix, k}, ".")] = v 253 } 254 255 return labels 256 } 257 258 func (c *containerConfig) mounts() []enginemount.Mount { 259 var r []enginemount.Mount 260 for _, mount := range c.spec().Mounts { 261 r = append(r, convertMount(mount)) 262 } 263 return r 264 } 265 266 func convertMount(m api.Mount) enginemount.Mount { 267 mount := enginemount.Mount{ 268 Source: m.Source, 269 Target: m.Target, 270 ReadOnly: m.ReadOnly, 271 } 272 273 switch m.Type { 274 case api.MountTypeBind: 275 mount.Type = enginemount.TypeBind 276 case api.MountTypeVolume: 277 mount.Type = enginemount.TypeVolume 278 case api.MountTypeTmpfs: 279 mount.Type = enginemount.TypeTmpfs 280 } 281 282 if m.BindOptions != nil { 283 mount.BindOptions = &enginemount.BindOptions{} 284 switch m.BindOptions.Propagation { 285 case api.MountPropagationRPrivate: 286 mount.BindOptions.Propagation = enginemount.PropagationRPrivate 287 case api.MountPropagationPrivate: 288 mount.BindOptions.Propagation = enginemount.PropagationPrivate 289 case api.MountPropagationRSlave: 290 mount.BindOptions.Propagation = enginemount.PropagationRSlave 291 case api.MountPropagationSlave: 292 mount.BindOptions.Propagation = enginemount.PropagationSlave 293 case api.MountPropagationRShared: 294 mount.BindOptions.Propagation = enginemount.PropagationRShared 295 case api.MountPropagationShared: 296 mount.BindOptions.Propagation = enginemount.PropagationShared 297 } 298 } 299 300 if m.VolumeOptions != nil { 301 mount.VolumeOptions = &enginemount.VolumeOptions{ 302 NoCopy: m.VolumeOptions.NoCopy, 303 } 304 if m.VolumeOptions.Labels != nil { 305 mount.VolumeOptions.Labels = make(map[string]string, len(m.VolumeOptions.Labels)) 306 for k, v := range m.VolumeOptions.Labels { 307 mount.VolumeOptions.Labels[k] = v 308 } 309 } 310 if m.VolumeOptions.DriverConfig != nil { 311 mount.VolumeOptions.DriverConfig = &enginemount.Driver{ 312 Name: m.VolumeOptions.DriverConfig.Name, 313 } 314 if m.VolumeOptions.DriverConfig.Options != nil { 315 mount.VolumeOptions.DriverConfig.Options = make(map[string]string, len(m.VolumeOptions.DriverConfig.Options)) 316 for k, v := range m.VolumeOptions.DriverConfig.Options { 317 mount.VolumeOptions.DriverConfig.Options[k] = v 318 } 319 } 320 } 321 } 322 323 if m.TmpfsOptions != nil { 324 mount.TmpfsOptions = &enginemount.TmpfsOptions{ 325 SizeBytes: m.TmpfsOptions.SizeBytes, 326 Mode: m.TmpfsOptions.Mode, 327 } 328 } 329 330 return mount 331 } 332 333 func (c *containerConfig) healthcheck() *enginecontainer.HealthConfig { 334 hcSpec := c.spec().Healthcheck 335 if hcSpec == nil { 336 return nil 337 } 338 interval, _ := gogotypes.DurationFromProto(hcSpec.Interval) 339 timeout, _ := gogotypes.DurationFromProto(hcSpec.Timeout) 340 startPeriod, _ := gogotypes.DurationFromProto(hcSpec.StartPeriod) 341 return &enginecontainer.HealthConfig{ 342 Test: hcSpec.Test, 343 Interval: interval, 344 Timeout: timeout, 345 Retries: int(hcSpec.Retries), 346 StartPeriod: startPeriod, 347 } 348 } 349 350 func (c *containerConfig) hostConfig() *enginecontainer.HostConfig { 351 hc := &enginecontainer.HostConfig{ 352 Resources: c.resources(), 353 GroupAdd: c.spec().Groups, 354 PortBindings: c.portBindings(), 355 Mounts: c.mounts(), 356 ReadonlyRootfs: c.spec().ReadOnly, 357 Isolation: c.isolation(), 358 } 359 360 if c.spec().DNSConfig != nil { 361 hc.DNS = c.spec().DNSConfig.Nameservers 362 hc.DNSSearch = c.spec().DNSConfig.Search 363 hc.DNSOptions = c.spec().DNSConfig.Options 364 } 365 366 c.applyPrivileges(hc) 367 368 // The format of extra hosts on swarmkit is specified in: 369 // http://man7.org/linux/man-pages/man5/hosts.5.html 370 // IP_address canonical_hostname [aliases...] 371 // However, the format of ExtraHosts in HostConfig is 372 // <host>:<ip> 373 // We need to do the conversion here 374 // (Alias is ignored for now) 375 for _, entry := range c.spec().Hosts { 376 parts := strings.Fields(entry) 377 if len(parts) > 1 { 378 hc.ExtraHosts = append(hc.ExtraHosts, fmt.Sprintf("%s:%s", parts[1], parts[0])) 379 } 380 } 381 382 if c.task.LogDriver != nil { 383 hc.LogConfig = enginecontainer.LogConfig{ 384 Type: c.task.LogDriver.Name, 385 Config: c.task.LogDriver.Options, 386 } 387 } 388 389 if len(c.task.Networks) > 0 { 390 labels := c.task.Networks[0].Network.Spec.Annotations.Labels 391 name := c.task.Networks[0].Network.Spec.Annotations.Name 392 if v, ok := labels["com.docker.swarm.predefined"]; ok && v == "true" { 393 hc.NetworkMode = enginecontainer.NetworkMode(name) 394 } 395 } 396 397 return hc 398 } 399 400 // This handles the case of volumes that are defined inside a service Mount 401 func (c *containerConfig) volumeCreateRequest(mount *api.Mount) *volumetypes.VolumesCreateBody { 402 var ( 403 driverName string 404 driverOpts map[string]string 405 labels map[string]string 406 ) 407 408 if mount.VolumeOptions != nil && mount.VolumeOptions.DriverConfig != nil { 409 driverName = mount.VolumeOptions.DriverConfig.Name 410 driverOpts = mount.VolumeOptions.DriverConfig.Options 411 labels = mount.VolumeOptions.Labels 412 } 413 414 if mount.VolumeOptions != nil { 415 return &volumetypes.VolumesCreateBody{ 416 Name: mount.Source, 417 Driver: driverName, 418 DriverOpts: driverOpts, 419 Labels: labels, 420 } 421 } 422 return nil 423 } 424 425 func (c *containerConfig) resources() enginecontainer.Resources { 426 resources := enginecontainer.Resources{} 427 428 // If no limits are specified let the engine use its defaults. 429 // 430 // TODO(aluzzardi): We might want to set some limits anyway otherwise 431 // "unlimited" tasks will step over the reservation of other tasks. 432 r := c.task.Spec.Resources 433 if r == nil || r.Limits == nil { 434 return resources 435 } 436 437 if r.Limits.MemoryBytes > 0 { 438 resources.Memory = r.Limits.MemoryBytes 439 } 440 441 if r.Limits.NanoCPUs > 0 { 442 // CPU Period must be set in microseconds. 443 resources.CPUPeriod = int64(cpuQuotaPeriod / time.Microsecond) 444 resources.CPUQuota = r.Limits.NanoCPUs * resources.CPUPeriod / 1e9 445 } 446 447 return resources 448 } 449 450 // Docker daemon supports just 1 network during container create. 451 func (c *containerConfig) createNetworkingConfig(b executorpkg.Backend) *network.NetworkingConfig { 452 var networks []*api.NetworkAttachment 453 if c.task.Spec.GetContainer() != nil || c.task.Spec.GetAttachment() != nil { 454 networks = c.task.Networks 455 } 456 457 epConfig := make(map[string]*network.EndpointSettings) 458 if len(networks) > 0 { 459 epConfig[networks[0].Network.Spec.Annotations.Name] = getEndpointConfig(networks[0], b) 460 } 461 462 return &network.NetworkingConfig{EndpointsConfig: epConfig} 463 } 464 465 // TODO: Merge this function with createNetworkingConfig after daemon supports multiple networks in container create 466 func (c *containerConfig) connectNetworkingConfig(b executorpkg.Backend) *network.NetworkingConfig { 467 var networks []*api.NetworkAttachment 468 if c.task.Spec.GetContainer() != nil { 469 networks = c.task.Networks 470 } 471 // First network is used during container create. Other networks are used in "docker network connect" 472 if len(networks) < 2 { 473 return nil 474 } 475 476 epConfig := make(map[string]*network.EndpointSettings) 477 for _, na := range networks[1:] { 478 epConfig[na.Network.Spec.Annotations.Name] = getEndpointConfig(na, b) 479 } 480 return &network.NetworkingConfig{EndpointsConfig: epConfig} 481 } 482 483 func getEndpointConfig(na *api.NetworkAttachment, b executorpkg.Backend) *network.EndpointSettings { 484 var ipv4, ipv6 string 485 for _, addr := range na.Addresses { 486 ip, _, err := net.ParseCIDR(addr) 487 if err != nil { 488 continue 489 } 490 491 if ip.To4() != nil { 492 ipv4 = ip.String() 493 continue 494 } 495 496 if ip.To16() != nil { 497 ipv6 = ip.String() 498 } 499 } 500 501 n := &network.EndpointSettings{ 502 NetworkID: na.Network.ID, 503 IPAMConfig: &network.EndpointIPAMConfig{ 504 IPv4Address: ipv4, 505 IPv6Address: ipv6, 506 }, 507 DriverOpts: na.DriverAttachmentOpts, 508 } 509 if v, ok := na.Network.Spec.Annotations.Labels["com.docker.swarm.predefined"]; ok && v == "true" { 510 if ln, err := b.FindNetwork(na.Network.Spec.Annotations.Name); err == nil { 511 n.NetworkID = ln.ID() 512 } 513 } 514 return n 515 } 516 517 func (c *containerConfig) virtualIP(networkID string) string { 518 if c.task.Endpoint == nil { 519 return "" 520 } 521 522 for _, eVip := range c.task.Endpoint.VirtualIPs { 523 // We only support IPv4 VIPs for now. 524 if eVip.NetworkID == networkID { 525 vip, _, err := net.ParseCIDR(eVip.Addr) 526 if err != nil { 527 return "" 528 } 529 530 return vip.String() 531 } 532 } 533 534 return "" 535 } 536 537 func (c *containerConfig) serviceConfig() *clustertypes.ServiceConfig { 538 if len(c.task.Networks) == 0 { 539 return nil 540 } 541 542 logrus.Debugf("Creating service config in agent for t = %+v", c.task) 543 svcCfg := &clustertypes.ServiceConfig{ 544 Name: c.task.ServiceAnnotations.Name, 545 Aliases: make(map[string][]string), 546 ID: c.task.ServiceID, 547 VirtualAddresses: make(map[string]*clustertypes.VirtualAddress), 548 } 549 550 for _, na := range c.task.Networks { 551 svcCfg.VirtualAddresses[na.Network.ID] = &clustertypes.VirtualAddress{ 552 // We support only IPv4 virtual IP for now. 553 IPv4: c.virtualIP(na.Network.ID), 554 } 555 if len(na.Aliases) > 0 { 556 svcCfg.Aliases[na.Network.ID] = na.Aliases 557 } 558 } 559 560 if c.task.Endpoint != nil { 561 for _, ePort := range c.task.Endpoint.Ports { 562 if ePort.PublishMode != api.PublishModeIngress { 563 continue 564 } 565 566 svcCfg.ExposedPorts = append(svcCfg.ExposedPorts, &clustertypes.PortConfig{ 567 Name: ePort.Name, 568 Protocol: int32(ePort.Protocol), 569 TargetPort: ePort.TargetPort, 570 PublishedPort: ePort.PublishedPort, 571 }) 572 } 573 } 574 575 return svcCfg 576 } 577 578 // networks returns a list of network names attached to the container. The 579 // returned name can be used to lookup the corresponding network create 580 // options. 581 func (c *containerConfig) networks() []string { 582 var networks []string 583 584 for name := range c.networksAttachments { 585 networks = append(networks, name) 586 } 587 588 return networks 589 } 590 591 func (c *containerConfig) networkCreateRequest(name string) (clustertypes.NetworkCreateRequest, error) { 592 na, ok := c.networksAttachments[name] 593 if !ok { 594 return clustertypes.NetworkCreateRequest{}, errors.New("container: unknown network referenced") 595 } 596 597 options := types.NetworkCreate{ 598 // ID: na.Network.ID, 599 Labels: na.Network.Spec.Annotations.Labels, 600 Internal: na.Network.Spec.Internal, 601 Attachable: na.Network.Spec.Attachable, 602 Ingress: convert.IsIngressNetwork(na.Network), 603 EnableIPv6: na.Network.Spec.Ipv6Enabled, 604 CheckDuplicate: true, 605 Scope: netconst.SwarmScope, 606 } 607 608 if na.Network.Spec.GetNetwork() != "" { 609 options.ConfigFrom = &network.ConfigReference{ 610 Network: na.Network.Spec.GetNetwork(), 611 } 612 } 613 614 if na.Network.DriverState != nil { 615 options.Driver = na.Network.DriverState.Name 616 options.Options = na.Network.DriverState.Options 617 } 618 if na.Network.IPAM != nil { 619 options.IPAM = &network.IPAM{ 620 Driver: na.Network.IPAM.Driver.Name, 621 Options: na.Network.IPAM.Driver.Options, 622 } 623 for _, ic := range na.Network.IPAM.Configs { 624 c := network.IPAMConfig{ 625 Subnet: ic.Subnet, 626 IPRange: ic.Range, 627 Gateway: ic.Gateway, 628 } 629 options.IPAM.Config = append(options.IPAM.Config, c) 630 } 631 } 632 633 return clustertypes.NetworkCreateRequest{ 634 ID: na.Network.ID, 635 NetworkCreateRequest: types.NetworkCreateRequest{ 636 Name: name, 637 NetworkCreate: options, 638 }, 639 }, nil 640 } 641 642 func (c *containerConfig) applyPrivileges(hc *enginecontainer.HostConfig) { 643 privileges := c.spec().Privileges 644 if privileges == nil { 645 return 646 } 647 648 credentials := privileges.CredentialSpec 649 if credentials != nil { 650 switch credentials.Source.(type) { 651 case *api.Privileges_CredentialSpec_File: 652 hc.SecurityOpt = append(hc.SecurityOpt, "credentialspec=file://"+credentials.GetFile()) 653 case *api.Privileges_CredentialSpec_Registry: 654 hc.SecurityOpt = append(hc.SecurityOpt, "credentialspec=registry://"+credentials.GetRegistry()) 655 } 656 } 657 658 selinux := privileges.SELinuxContext 659 if selinux != nil { 660 if selinux.Disable { 661 hc.SecurityOpt = append(hc.SecurityOpt, "label=disable") 662 } 663 if selinux.User != "" { 664 hc.SecurityOpt = append(hc.SecurityOpt, "label=user:"+selinux.User) 665 } 666 if selinux.Role != "" { 667 hc.SecurityOpt = append(hc.SecurityOpt, "label=role:"+selinux.Role) 668 } 669 if selinux.Level != "" { 670 hc.SecurityOpt = append(hc.SecurityOpt, "label=level:"+selinux.Level) 671 } 672 if selinux.Type != "" { 673 hc.SecurityOpt = append(hc.SecurityOpt, "label=type:"+selinux.Type) 674 } 675 } 676 } 677 678 func (c containerConfig) eventFilter() filters.Args { 679 filter := filters.NewArgs() 680 filter.Add("type", events.ContainerEventType) 681 filter.Add("name", c.name()) 682 filter.Add("label", fmt.Sprintf("%v.task.id=%v", systemLabelPrefix, c.task.ID)) 683 return filter 684 }