service_create.go 7.0 KB

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