container.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package container
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/api/types"
  11. enginecontainer "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/events"
  13. "github.com/docker/docker/api/types/filters"
  14. enginemount "github.com/docker/docker/api/types/mount"
  15. "github.com/docker/docker/api/types/network"
  16. volumetypes "github.com/docker/docker/api/types/volume"
  17. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  18. "github.com/docker/docker/reference"
  19. "github.com/docker/go-connections/nat"
  20. "github.com/docker/swarmkit/agent/exec"
  21. "github.com/docker/swarmkit/api"
  22. "github.com/docker/swarmkit/protobuf/ptypes"
  23. "github.com/docker/swarmkit/template"
  24. )
  25. const (
  26. // Explicitly use the kernel's default setting for CPU quota of 100ms.
  27. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  28. cpuQuotaPeriod = 100 * time.Millisecond
  29. // systemLabelPrefix represents the reserved namespace for system labels.
  30. systemLabelPrefix = "com.docker.swarm"
  31. )
  32. // containerConfig converts task properties into docker container compatible
  33. // components.
  34. type containerConfig struct {
  35. task *api.Task
  36. networksAttachments map[string]*api.NetworkAttachment
  37. }
  38. // newContainerConfig returns a validated container config. No methods should
  39. // return an error if this function returns without error.
  40. func newContainerConfig(t *api.Task) (*containerConfig, error) {
  41. var c containerConfig
  42. return &c, c.setTask(t)
  43. }
  44. func (c *containerConfig) setTask(t *api.Task) error {
  45. if t.Spec.GetContainer() == nil && t.Spec.GetAttachment() == nil {
  46. return exec.ErrRuntimeUnsupported
  47. }
  48. container := t.Spec.GetContainer()
  49. if container != nil {
  50. if container.Image == "" {
  51. return ErrImageRequired
  52. }
  53. if err := validateMounts(container.Mounts); err != nil {
  54. return err
  55. }
  56. }
  57. // index the networks by name
  58. c.networksAttachments = make(map[string]*api.NetworkAttachment, len(t.Networks))
  59. for _, attachment := range t.Networks {
  60. c.networksAttachments[attachment.Network.Spec.Annotations.Name] = attachment
  61. }
  62. c.task = t
  63. if t.Spec.GetContainer() != nil {
  64. preparedSpec, err := template.ExpandContainerSpec(t)
  65. if err != nil {
  66. return err
  67. }
  68. c.task.Spec.Runtime = &api.TaskSpec_Container{
  69. Container: preparedSpec,
  70. }
  71. }
  72. return nil
  73. }
  74. func (c *containerConfig) id() string {
  75. attachment := c.task.Spec.GetAttachment()
  76. if attachment == nil {
  77. return ""
  78. }
  79. return attachment.ContainerID
  80. }
  81. func (c *containerConfig) taskID() string {
  82. return c.task.ID
  83. }
  84. func (c *containerConfig) endpoint() *api.Endpoint {
  85. return c.task.Endpoint
  86. }
  87. func (c *containerConfig) spec() *api.ContainerSpec {
  88. return c.task.Spec.GetContainer()
  89. }
  90. func (c *containerConfig) nameOrID() string {
  91. if c.task.Spec.GetContainer() != nil {
  92. return c.name()
  93. }
  94. return c.id()
  95. }
  96. func (c *containerConfig) name() string {
  97. if c.task.Annotations.Name != "" {
  98. // if set, use the container Annotations.Name field, set in the orchestrator.
  99. return c.task.Annotations.Name
  100. }
  101. slot := fmt.Sprint(c.task.Slot)
  102. if slot == "" || c.task.Slot == 0 {
  103. slot = c.task.NodeID
  104. }
  105. // fallback to service.slot.id.
  106. return fmt.Sprintf("%s.%s.%s", c.task.ServiceAnnotations.Name, slot, c.task.ID)
  107. }
  108. func (c *containerConfig) image() string {
  109. raw := c.spec().Image
  110. ref, err := reference.ParseNamed(raw)
  111. if err != nil {
  112. return raw
  113. }
  114. return reference.WithDefaultTag(ref).String()
  115. }
  116. func (c *containerConfig) portBindings() nat.PortMap {
  117. portBindings := nat.PortMap{}
  118. if c.task.Endpoint == nil {
  119. return portBindings
  120. }
  121. for _, portConfig := range c.task.Endpoint.Ports {
  122. if portConfig.PublishMode != api.PublishModeHost {
  123. continue
  124. }
  125. port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String())))
  126. binding := []nat.PortBinding{
  127. {},
  128. }
  129. if portConfig.PublishedPort != 0 {
  130. binding[0].HostPort = strconv.Itoa(int(portConfig.PublishedPort))
  131. }
  132. portBindings[port] = binding
  133. }
  134. return portBindings
  135. }
  136. func (c *containerConfig) exposedPorts() map[nat.Port]struct{} {
  137. exposedPorts := make(map[nat.Port]struct{})
  138. if c.task.Endpoint == nil {
  139. return exposedPorts
  140. }
  141. for _, portConfig := range c.task.Endpoint.Ports {
  142. if portConfig.PublishMode != api.PublishModeHost {
  143. continue
  144. }
  145. port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String())))
  146. exposedPorts[port] = struct{}{}
  147. }
  148. return exposedPorts
  149. }
  150. func (c *containerConfig) config() *enginecontainer.Config {
  151. config := &enginecontainer.Config{
  152. Labels: c.labels(),
  153. Tty: c.spec().TTY,
  154. OpenStdin: c.spec().OpenStdin,
  155. User: c.spec().User,
  156. Env: c.spec().Env,
  157. Hostname: c.spec().Hostname,
  158. WorkingDir: c.spec().Dir,
  159. Image: c.image(),
  160. ExposedPorts: c.exposedPorts(),
  161. Healthcheck: c.healthcheck(),
  162. }
  163. if len(c.spec().Command) > 0 {
  164. // If Command is provided, we replace the whole invocation with Command
  165. // by replacing Entrypoint and specifying Cmd. Args is ignored in this
  166. // case.
  167. config.Entrypoint = append(config.Entrypoint, c.spec().Command...)
  168. config.Cmd = append(config.Cmd, c.spec().Args...)
  169. } else if len(c.spec().Args) > 0 {
  170. // In this case, we assume the image has an Entrypoint and Args
  171. // specifies the arguments for that entrypoint.
  172. config.Cmd = c.spec().Args
  173. }
  174. return config
  175. }
  176. func (c *containerConfig) labels() map[string]string {
  177. var (
  178. system = map[string]string{
  179. "task": "", // mark as cluster task
  180. "task.id": c.task.ID,
  181. "task.name": c.name(),
  182. "node.id": c.task.NodeID,
  183. "service.id": c.task.ServiceID,
  184. "service.name": c.task.ServiceAnnotations.Name,
  185. }
  186. labels = make(map[string]string)
  187. )
  188. // base labels are those defined in the spec.
  189. for k, v := range c.spec().Labels {
  190. labels[k] = v
  191. }
  192. // we then apply the overrides from the task, which may be set via the
  193. // orchestrator.
  194. for k, v := range c.task.Annotations.Labels {
  195. labels[k] = v
  196. }
  197. // finally, we apply the system labels, which override all labels.
  198. for k, v := range system {
  199. labels[strings.Join([]string{systemLabelPrefix, k}, ".")] = v
  200. }
  201. return labels
  202. }
  203. func (c *containerConfig) mounts() []enginemount.Mount {
  204. var r []enginemount.Mount
  205. for _, mount := range c.spec().Mounts {
  206. r = append(r, convertMount(mount))
  207. }
  208. return r
  209. }
  210. func convertMount(m api.Mount) enginemount.Mount {
  211. mount := enginemount.Mount{
  212. Source: m.Source,
  213. Target: m.Target,
  214. ReadOnly: m.ReadOnly,
  215. }
  216. switch m.Type {
  217. case api.MountTypeBind:
  218. mount.Type = enginemount.TypeBind
  219. case api.MountTypeVolume:
  220. mount.Type = enginemount.TypeVolume
  221. case api.MountTypeTmpfs:
  222. mount.Type = enginemount.TypeTmpfs
  223. }
  224. if m.BindOptions != nil {
  225. mount.BindOptions = &enginemount.BindOptions{}
  226. switch m.BindOptions.Propagation {
  227. case api.MountPropagationRPrivate:
  228. mount.BindOptions.Propagation = enginemount.PropagationRPrivate
  229. case api.MountPropagationPrivate:
  230. mount.BindOptions.Propagation = enginemount.PropagationPrivate
  231. case api.MountPropagationRSlave:
  232. mount.BindOptions.Propagation = enginemount.PropagationRSlave
  233. case api.MountPropagationSlave:
  234. mount.BindOptions.Propagation = enginemount.PropagationSlave
  235. case api.MountPropagationRShared:
  236. mount.BindOptions.Propagation = enginemount.PropagationRShared
  237. case api.MountPropagationShared:
  238. mount.BindOptions.Propagation = enginemount.PropagationShared
  239. }
  240. }
  241. if m.VolumeOptions != nil {
  242. mount.VolumeOptions = &enginemount.VolumeOptions{
  243. NoCopy: m.VolumeOptions.NoCopy,
  244. }
  245. if m.VolumeOptions.Labels != nil {
  246. mount.VolumeOptions.Labels = make(map[string]string, len(m.VolumeOptions.Labels))
  247. for k, v := range m.VolumeOptions.Labels {
  248. mount.VolumeOptions.Labels[k] = v
  249. }
  250. }
  251. if m.VolumeOptions.DriverConfig != nil {
  252. mount.VolumeOptions.DriverConfig = &enginemount.Driver{
  253. Name: m.VolumeOptions.DriverConfig.Name,
  254. }
  255. if m.VolumeOptions.DriverConfig.Options != nil {
  256. mount.VolumeOptions.DriverConfig.Options = make(map[string]string, len(m.VolumeOptions.DriverConfig.Options))
  257. for k, v := range m.VolumeOptions.DriverConfig.Options {
  258. mount.VolumeOptions.DriverConfig.Options[k] = v
  259. }
  260. }
  261. }
  262. }
  263. if m.TmpfsOptions != nil {
  264. mount.TmpfsOptions = &enginemount.TmpfsOptions{
  265. SizeBytes: m.TmpfsOptions.SizeBytes,
  266. Mode: m.TmpfsOptions.Mode,
  267. }
  268. }
  269. return mount
  270. }
  271. func (c *containerConfig) healthcheck() *enginecontainer.HealthConfig {
  272. hcSpec := c.spec().Healthcheck
  273. if hcSpec == nil {
  274. return nil
  275. }
  276. interval, _ := ptypes.Duration(hcSpec.Interval)
  277. timeout, _ := ptypes.Duration(hcSpec.Timeout)
  278. return &enginecontainer.HealthConfig{
  279. Test: hcSpec.Test,
  280. Interval: interval,
  281. Timeout: timeout,
  282. Retries: int(hcSpec.Retries),
  283. }
  284. }
  285. func (c *containerConfig) hostConfig() *enginecontainer.HostConfig {
  286. hc := &enginecontainer.HostConfig{
  287. Resources: c.resources(),
  288. GroupAdd: c.spec().Groups,
  289. PortBindings: c.portBindings(),
  290. Mounts: c.mounts(),
  291. }
  292. if c.spec().DNSConfig != nil {
  293. hc.DNS = c.spec().DNSConfig.Nameservers
  294. hc.DNSSearch = c.spec().DNSConfig.Search
  295. hc.DNSOptions = c.spec().DNSConfig.Options
  296. }
  297. // The format of extra hosts on swarmkit is specified in:
  298. // http://man7.org/linux/man-pages/man5/hosts.5.html
  299. // IP_address canonical_hostname [aliases...]
  300. // However, the format of ExtraHosts in HostConfig is
  301. // <host>:<ip>
  302. // We need to do the conversion here
  303. // (Alias is ignored for now)
  304. for _, entry := range c.spec().Hosts {
  305. parts := strings.Fields(entry)
  306. if len(parts) > 1 {
  307. hc.ExtraHosts = append(hc.ExtraHosts, fmt.Sprintf("%s:%s", parts[1], parts[0]))
  308. }
  309. }
  310. if c.task.LogDriver != nil {
  311. hc.LogConfig = enginecontainer.LogConfig{
  312. Type: c.task.LogDriver.Name,
  313. Config: c.task.LogDriver.Options,
  314. }
  315. }
  316. return hc
  317. }
  318. // This handles the case of volumes that are defined inside a service Mount
  319. func (c *containerConfig) volumeCreateRequest(mount *api.Mount) *volumetypes.VolumesCreateBody {
  320. var (
  321. driverName string
  322. driverOpts map[string]string
  323. labels map[string]string
  324. )
  325. if mount.VolumeOptions != nil && mount.VolumeOptions.DriverConfig != nil {
  326. driverName = mount.VolumeOptions.DriverConfig.Name
  327. driverOpts = mount.VolumeOptions.DriverConfig.Options
  328. labels = mount.VolumeOptions.Labels
  329. }
  330. if mount.VolumeOptions != nil {
  331. return &volumetypes.VolumesCreateBody{
  332. Name: mount.Source,
  333. Driver: driverName,
  334. DriverOpts: driverOpts,
  335. Labels: labels,
  336. }
  337. }
  338. return nil
  339. }
  340. func (c *containerConfig) resources() enginecontainer.Resources {
  341. resources := enginecontainer.Resources{}
  342. // If no limits are specified let the engine use its defaults.
  343. //
  344. // TODO(aluzzardi): We might want to set some limits anyway otherwise
  345. // "unlimited" tasks will step over the reservation of other tasks.
  346. r := c.task.Spec.Resources
  347. if r == nil || r.Limits == nil {
  348. return resources
  349. }
  350. if r.Limits.MemoryBytes > 0 {
  351. resources.Memory = r.Limits.MemoryBytes
  352. }
  353. if r.Limits.NanoCPUs > 0 {
  354. // CPU Period must be set in microseconds.
  355. resources.CPUPeriod = int64(cpuQuotaPeriod / time.Microsecond)
  356. resources.CPUQuota = r.Limits.NanoCPUs * resources.CPUPeriod / 1e9
  357. }
  358. return resources
  359. }
  360. // Docker daemon supports just 1 network during container create.
  361. func (c *containerConfig) createNetworkingConfig() *network.NetworkingConfig {
  362. var networks []*api.NetworkAttachment
  363. if c.task.Spec.GetContainer() != nil || c.task.Spec.GetAttachment() != nil {
  364. networks = c.task.Networks
  365. }
  366. epConfig := make(map[string]*network.EndpointSettings)
  367. if len(networks) > 0 {
  368. epConfig[networks[0].Network.Spec.Annotations.Name] = getEndpointConfig(networks[0])
  369. }
  370. return &network.NetworkingConfig{EndpointsConfig: epConfig}
  371. }
  372. // TODO: Merge this function with createNetworkingConfig after daemon supports multiple networks in container create
  373. func (c *containerConfig) connectNetworkingConfig() *network.NetworkingConfig {
  374. var networks []*api.NetworkAttachment
  375. if c.task.Spec.GetContainer() != nil {
  376. networks = c.task.Networks
  377. }
  378. // First network is used during container create. Other networks are used in "docker network connect"
  379. if len(networks) < 2 {
  380. return nil
  381. }
  382. epConfig := make(map[string]*network.EndpointSettings)
  383. for _, na := range networks[1:] {
  384. epConfig[na.Network.Spec.Annotations.Name] = getEndpointConfig(na)
  385. }
  386. return &network.NetworkingConfig{EndpointsConfig: epConfig}
  387. }
  388. func getEndpointConfig(na *api.NetworkAttachment) *network.EndpointSettings {
  389. var ipv4, ipv6 string
  390. for _, addr := range na.Addresses {
  391. ip, _, err := net.ParseCIDR(addr)
  392. if err != nil {
  393. continue
  394. }
  395. if ip.To4() != nil {
  396. ipv4 = ip.String()
  397. continue
  398. }
  399. if ip.To16() != nil {
  400. ipv6 = ip.String()
  401. }
  402. }
  403. return &network.EndpointSettings{
  404. NetworkID: na.Network.ID,
  405. IPAMConfig: &network.EndpointIPAMConfig{
  406. IPv4Address: ipv4,
  407. IPv6Address: ipv6,
  408. },
  409. }
  410. }
  411. func (c *containerConfig) virtualIP(networkID string) string {
  412. if c.task.Endpoint == nil {
  413. return ""
  414. }
  415. for _, eVip := range c.task.Endpoint.VirtualIPs {
  416. // We only support IPv4 VIPs for now.
  417. if eVip.NetworkID == networkID {
  418. vip, _, err := net.ParseCIDR(eVip.Addr)
  419. if err != nil {
  420. return ""
  421. }
  422. return vip.String()
  423. }
  424. }
  425. return ""
  426. }
  427. func (c *containerConfig) serviceConfig() *clustertypes.ServiceConfig {
  428. if len(c.task.Networks) == 0 {
  429. return nil
  430. }
  431. logrus.Debugf("Creating service config in agent for t = %+v", c.task)
  432. svcCfg := &clustertypes.ServiceConfig{
  433. Name: c.task.ServiceAnnotations.Name,
  434. Aliases: make(map[string][]string),
  435. ID: c.task.ServiceID,
  436. VirtualAddresses: make(map[string]*clustertypes.VirtualAddress),
  437. }
  438. for _, na := range c.task.Networks {
  439. svcCfg.VirtualAddresses[na.Network.ID] = &clustertypes.VirtualAddress{
  440. // We support only IPv4 virtual IP for now.
  441. IPv4: c.virtualIP(na.Network.ID),
  442. }
  443. if len(na.Aliases) > 0 {
  444. svcCfg.Aliases[na.Network.ID] = na.Aliases
  445. }
  446. }
  447. if c.task.Endpoint != nil {
  448. for _, ePort := range c.task.Endpoint.Ports {
  449. if ePort.PublishMode != api.PublishModeIngress {
  450. continue
  451. }
  452. svcCfg.ExposedPorts = append(svcCfg.ExposedPorts, &clustertypes.PortConfig{
  453. Name: ePort.Name,
  454. Protocol: int32(ePort.Protocol),
  455. TargetPort: ePort.TargetPort,
  456. PublishedPort: ePort.PublishedPort,
  457. })
  458. }
  459. }
  460. return svcCfg
  461. }
  462. // networks returns a list of network names attached to the container. The
  463. // returned name can be used to lookup the corresponding network create
  464. // options.
  465. func (c *containerConfig) networks() []string {
  466. var networks []string
  467. for name := range c.networksAttachments {
  468. networks = append(networks, name)
  469. }
  470. return networks
  471. }
  472. func (c *containerConfig) networkCreateRequest(name string) (clustertypes.NetworkCreateRequest, error) {
  473. na, ok := c.networksAttachments[name]
  474. if !ok {
  475. return clustertypes.NetworkCreateRequest{}, errors.New("container: unknown network referenced")
  476. }
  477. options := types.NetworkCreate{
  478. // ID: na.Network.ID,
  479. Driver: na.Network.DriverState.Name,
  480. IPAM: &network.IPAM{
  481. Driver: na.Network.IPAM.Driver.Name,
  482. },
  483. Options: na.Network.DriverState.Options,
  484. Labels: na.Network.Spec.Annotations.Labels,
  485. Internal: na.Network.Spec.Internal,
  486. Attachable: na.Network.Spec.Attachable,
  487. EnableIPv6: na.Network.Spec.Ipv6Enabled,
  488. CheckDuplicate: true,
  489. }
  490. for _, ic := range na.Network.IPAM.Configs {
  491. c := network.IPAMConfig{
  492. Subnet: ic.Subnet,
  493. IPRange: ic.Range,
  494. Gateway: ic.Gateway,
  495. }
  496. options.IPAM.Config = append(options.IPAM.Config, c)
  497. }
  498. return clustertypes.NetworkCreateRequest{
  499. ID: na.Network.ID,
  500. NetworkCreateRequest: types.NetworkCreateRequest{
  501. Name: name,
  502. NetworkCreate: options,
  503. },
  504. }, nil
  505. }
  506. func (c containerConfig) eventFilter() filters.Args {
  507. filter := filters.NewArgs()
  508. filter.Add("type", events.ContainerEventType)
  509. filter.Add("name", c.name())
  510. filter.Add("label", fmt.Sprintf("%v.task.id=%v", systemLabelPrefix, c.task.ID))
  511. return filter
  512. }