service_create.go 6.5 KB

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