service_create.go 6.8 KB

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