deploy.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package stack
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/spf13/cobra"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/api/types/swarm"
  9. "github.com/docker/docker/cli"
  10. "github.com/docker/docker/cli/command"
  11. "github.com/docker/docker/cli/command/bundlefile"
  12. )
  13. const (
  14. defaultNetworkDriver = "overlay"
  15. )
  16. type deployOptions struct {
  17. bundlefile string
  18. namespace string
  19. sendRegistryAuth bool
  20. }
  21. func newDeployCommand(dockerCli *command.DockerCli) *cobra.Command {
  22. var opts deployOptions
  23. cmd := &cobra.Command{
  24. Use: "deploy [OPTIONS] STACK",
  25. Aliases: []string{"up"},
  26. Short: "Create and update a stack from a Distributed Application Bundle (DAB)",
  27. Args: cli.ExactArgs(1),
  28. RunE: func(cmd *cobra.Command, args []string) error {
  29. opts.namespace = strings.TrimSuffix(args[0], ".dab")
  30. return runDeploy(dockerCli, opts)
  31. },
  32. Tags: map[string]string{"experimental": "", "version": "1.25"},
  33. }
  34. flags := cmd.Flags()
  35. addBundlefileFlag(&opts.bundlefile, flags)
  36. addRegistryAuthFlag(&opts.sendRegistryAuth, flags)
  37. return cmd
  38. }
  39. func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
  40. bundle, err := loadBundlefile(dockerCli.Err(), opts.namespace, opts.bundlefile)
  41. if err != nil {
  42. return err
  43. }
  44. info, err := dockerCli.Client().Info(context.Background())
  45. if err != nil {
  46. return err
  47. }
  48. if !info.Swarm.ControlAvailable {
  49. return fmt.Errorf("This node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again.")
  50. }
  51. networks := getUniqueNetworkNames(bundle.Services)
  52. ctx := context.Background()
  53. if err := updateNetworks(ctx, dockerCli, networks, opts.namespace); err != nil {
  54. return err
  55. }
  56. return deployServices(ctx, dockerCli, bundle.Services, opts.namespace, opts.sendRegistryAuth)
  57. }
  58. func getUniqueNetworkNames(services map[string]bundlefile.Service) []string {
  59. networkSet := make(map[string]bool)
  60. for _, service := range services {
  61. for _, network := range service.Networks {
  62. networkSet[network] = true
  63. }
  64. }
  65. networks := []string{}
  66. for network := range networkSet {
  67. networks = append(networks, network)
  68. }
  69. return networks
  70. }
  71. func updateNetworks(
  72. ctx context.Context,
  73. dockerCli *command.DockerCli,
  74. networks []string,
  75. namespace string,
  76. ) error {
  77. client := dockerCli.Client()
  78. existingNetworks, err := getNetworks(ctx, client, namespace)
  79. if err != nil {
  80. return err
  81. }
  82. existingNetworkMap := make(map[string]types.NetworkResource)
  83. for _, network := range existingNetworks {
  84. existingNetworkMap[network.Name] = network
  85. }
  86. createOpts := types.NetworkCreate{
  87. Labels: getStackLabels(namespace, nil),
  88. Driver: defaultNetworkDriver,
  89. }
  90. for _, internalName := range networks {
  91. name := fmt.Sprintf("%s_%s", namespace, internalName)
  92. if _, exists := existingNetworkMap[name]; exists {
  93. continue
  94. }
  95. fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name)
  96. if _, err := client.NetworkCreate(ctx, name, createOpts); err != nil {
  97. return err
  98. }
  99. }
  100. return nil
  101. }
  102. func convertNetworks(networks []string, namespace string, name string) []swarm.NetworkAttachmentConfig {
  103. nets := []swarm.NetworkAttachmentConfig{}
  104. for _, network := range networks {
  105. nets = append(nets, swarm.NetworkAttachmentConfig{
  106. Target: namespace + "_" + network,
  107. Aliases: []string{name},
  108. })
  109. }
  110. return nets
  111. }
  112. func deployServices(
  113. ctx context.Context,
  114. dockerCli *command.DockerCli,
  115. services map[string]bundlefile.Service,
  116. namespace string,
  117. sendAuth bool,
  118. ) error {
  119. apiClient := dockerCli.Client()
  120. out := dockerCli.Out()
  121. existingServices, err := getServices(ctx, apiClient, namespace)
  122. if err != nil {
  123. return err
  124. }
  125. existingServiceMap := make(map[string]swarm.Service)
  126. for _, service := range existingServices {
  127. existingServiceMap[service.Spec.Name] = service
  128. }
  129. for internalName, service := range services {
  130. name := fmt.Sprintf("%s_%s", namespace, internalName)
  131. var ports []swarm.PortConfig
  132. for _, portSpec := range service.Ports {
  133. ports = append(ports, swarm.PortConfig{
  134. Protocol: swarm.PortConfigProtocol(portSpec.Protocol),
  135. TargetPort: portSpec.Port,
  136. })
  137. }
  138. serviceSpec := swarm.ServiceSpec{
  139. Annotations: swarm.Annotations{
  140. Name: name,
  141. Labels: getStackLabels(namespace, service.Labels),
  142. },
  143. TaskTemplate: swarm.TaskSpec{
  144. ContainerSpec: swarm.ContainerSpec{
  145. Image: service.Image,
  146. Command: service.Command,
  147. Args: service.Args,
  148. Env: service.Env,
  149. // Service Labels will not be copied to Containers
  150. // automatically during the deployment so we apply
  151. // it here.
  152. Labels: getStackLabels(namespace, nil),
  153. },
  154. },
  155. EndpointSpec: &swarm.EndpointSpec{
  156. Ports: ports,
  157. },
  158. Networks: convertNetworks(service.Networks, namespace, internalName),
  159. }
  160. cspec := &serviceSpec.TaskTemplate.ContainerSpec
  161. if service.WorkingDir != nil {
  162. cspec.Dir = *service.WorkingDir
  163. }
  164. if service.User != nil {
  165. cspec.User = *service.User
  166. }
  167. encodedAuth := ""
  168. if sendAuth {
  169. // Retrieve encoded auth token from the image reference
  170. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  171. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  172. if err != nil {
  173. return err
  174. }
  175. }
  176. if service, exists := existingServiceMap[name]; exists {
  177. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  178. updateOpts := types.ServiceUpdateOptions{}
  179. if sendAuth {
  180. updateOpts.EncodedRegistryAuth = encodedAuth
  181. }
  182. if err := apiClient.ServiceUpdate(
  183. ctx,
  184. service.ID,
  185. service.Version,
  186. serviceSpec,
  187. updateOpts,
  188. ); err != nil {
  189. return err
  190. }
  191. } else {
  192. fmt.Fprintf(out, "Creating service %s\n", name)
  193. createOpts := types.ServiceCreateOptions{}
  194. if sendAuth {
  195. createOpts.EncodedRegistryAuth = encodedAuth
  196. }
  197. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  198. return err
  199. }
  200. }
  201. }
  202. return nil
  203. }