service_create.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "github.com/docker/distribution/reference"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/registry"
  10. "github.com/docker/docker/api/types/swarm"
  11. "github.com/opencontainers/go-digest"
  12. "github.com/pkg/errors"
  13. )
  14. // ServiceCreate creates a new service.
  15. func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) {
  16. var response types.ServiceCreateResponse
  17. headers := map[string][]string{
  18. "version": {cli.version},
  19. }
  20. if options.EncodedRegistryAuth != "" {
  21. headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth}
  22. }
  23. // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container
  24. if service.TaskTemplate.ContainerSpec == nil && (service.TaskTemplate.Runtime == "" || service.TaskTemplate.Runtime == swarm.RuntimeContainer) {
  25. service.TaskTemplate.ContainerSpec = &swarm.ContainerSpec{}
  26. }
  27. if err := validateServiceSpec(service); err != nil {
  28. return response, err
  29. }
  30. // ensure that the image is tagged
  31. var resolveWarning string
  32. switch {
  33. case service.TaskTemplate.ContainerSpec != nil:
  34. if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" {
  35. service.TaskTemplate.ContainerSpec.Image = taggedImg
  36. }
  37. if options.QueryRegistry {
  38. resolveWarning = resolveContainerSpecImage(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth)
  39. }
  40. case service.TaskTemplate.PluginSpec != nil:
  41. if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" {
  42. service.TaskTemplate.PluginSpec.Remote = taggedImg
  43. }
  44. if options.QueryRegistry {
  45. resolveWarning = resolvePluginSpecRemote(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth)
  46. }
  47. }
  48. resp, err := cli.post(ctx, "/services/create", nil, service, headers)
  49. defer ensureReaderClosed(resp)
  50. if err != nil {
  51. return response, err
  52. }
  53. err = json.NewDecoder(resp.body).Decode(&response)
  54. if resolveWarning != "" {
  55. response.Warnings = append(response.Warnings, resolveWarning)
  56. }
  57. return response, err
  58. }
  59. func resolveContainerSpecImage(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string {
  60. var warning string
  61. if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.ContainerSpec.Image, encodedAuth); err != nil {
  62. warning = digestWarning(taskSpec.ContainerSpec.Image)
  63. } else {
  64. taskSpec.ContainerSpec.Image = img
  65. if len(imgPlatforms) > 0 {
  66. if taskSpec.Placement == nil {
  67. taskSpec.Placement = &swarm.Placement{}
  68. }
  69. taskSpec.Placement.Platforms = imgPlatforms
  70. }
  71. }
  72. return warning
  73. }
  74. func resolvePluginSpecRemote(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string {
  75. var warning string
  76. if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.PluginSpec.Remote, encodedAuth); err != nil {
  77. warning = digestWarning(taskSpec.PluginSpec.Remote)
  78. } else {
  79. taskSpec.PluginSpec.Remote = img
  80. if len(imgPlatforms) > 0 {
  81. if taskSpec.Placement == nil {
  82. taskSpec.Placement = &swarm.Placement{}
  83. }
  84. taskSpec.Placement.Platforms = imgPlatforms
  85. }
  86. }
  87. return warning
  88. }
  89. func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, image, encodedAuth string) (string, []swarm.Platform, error) {
  90. distributionInspect, err := cli.DistributionInspect(ctx, image, encodedAuth)
  91. var platforms []swarm.Platform
  92. if err != nil {
  93. return "", nil, err
  94. }
  95. imageWithDigest := imageWithDigestString(image, distributionInspect.Descriptor.Digest)
  96. if len(distributionInspect.Platforms) > 0 {
  97. platforms = make([]swarm.Platform, 0, len(distributionInspect.Platforms))
  98. for _, p := range distributionInspect.Platforms {
  99. // clear architecture field for arm. This is a temporary patch to address
  100. // https://github.com/docker/swarmkit/issues/2294. The issue is that while
  101. // image manifests report "arm" as the architecture, the node reports
  102. // something like "armv7l" (includes the variant), which causes arm images
  103. // to stop working with swarm mode. This patch removes the architecture
  104. // constraint for arm images to ensure tasks get scheduled.
  105. arch := p.Architecture
  106. if strings.ToLower(arch) == "arm" {
  107. arch = ""
  108. }
  109. platforms = append(platforms, swarm.Platform{
  110. Architecture: arch,
  111. OS: p.OS,
  112. })
  113. }
  114. }
  115. return imageWithDigest, platforms, err
  116. }
  117. // imageWithDigestString takes an image string and a digest, and updates
  118. // the image string if it didn't originally contain a digest. It returns
  119. // image unmodified in other situations.
  120. func imageWithDigestString(image string, dgst digest.Digest) string {
  121. namedRef, err := reference.ParseNormalizedNamed(image)
  122. if err == nil {
  123. if _, isCanonical := namedRef.(reference.Canonical); !isCanonical {
  124. // ensure that image gets a default tag if none is provided
  125. img, err := reference.WithDigest(namedRef, dgst)
  126. if err == nil {
  127. return reference.FamiliarString(img)
  128. }
  129. }
  130. }
  131. return image
  132. }
  133. // imageWithTagString takes an image string, and returns a tagged image
  134. // string, adding a 'latest' tag if one was not provided. It returns an
  135. // empty string if a canonical reference was provided
  136. func imageWithTagString(image string) string {
  137. namedRef, err := reference.ParseNormalizedNamed(image)
  138. if err == nil {
  139. return reference.FamiliarString(reference.TagNameOnly(namedRef))
  140. }
  141. return ""
  142. }
  143. // digestWarning constructs a formatted warning string using the
  144. // image name that could not be pinned by digest. The formatting
  145. // is hardcoded, but could me made smarter in the future
  146. func digestWarning(image string) string {
  147. return fmt.Sprintf("image %s could not be accessed on a registry to record\nits digest. Each node will access %s independently,\npossibly leading to different nodes running different\nversions of the image.\n", image, image)
  148. }
  149. func validateServiceSpec(s swarm.ServiceSpec) error {
  150. if s.TaskTemplate.ContainerSpec != nil && s.TaskTemplate.PluginSpec != nil {
  151. return errors.New("must not specify both a container spec and a plugin spec in the task template")
  152. }
  153. if s.TaskTemplate.PluginSpec != nil && s.TaskTemplate.Runtime != swarm.RuntimePlugin {
  154. return errors.New("mismatched runtime with plugin spec")
  155. }
  156. if s.TaskTemplate.ContainerSpec != nil && (s.TaskTemplate.Runtime != "" && s.TaskTemplate.Runtime != swarm.RuntimeContainer) {
  157. return errors.New("mismatched runtime with container spec")
  158. }
  159. return nil
  160. }