service_create.go 6.8 KB

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