container.go 20 KB

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