create.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package service
  2. import (
  3. "fmt"
  4. "github.com/docker/docker/api/client"
  5. "github.com/docker/docker/cli"
  6. "github.com/docker/engine-api/types"
  7. "github.com/spf13/cobra"
  8. "golang.org/x/net/context"
  9. )
  10. func newCreateCommand(dockerCli *client.DockerCli) *cobra.Command {
  11. opts := newServiceOptions()
  12. cmd := &cobra.Command{
  13. Use: "create [OPTIONS] IMAGE [COMMAND] [ARG...]",
  14. Short: "Create a new service",
  15. Args: cli.RequiresMinArgs(1),
  16. RunE: func(cmd *cobra.Command, args []string) error {
  17. opts.image = args[0]
  18. if len(args) > 1 {
  19. opts.args = args[1:]
  20. }
  21. return runCreate(dockerCli, opts)
  22. },
  23. }
  24. flags := cmd.Flags()
  25. flags.StringVar(&opts.mode, flagMode, "replicated", "Service mode (replicated or global)")
  26. addServiceFlags(cmd, opts)
  27. flags.VarP(&opts.labels, flagLabel, "l", "Service labels")
  28. flags.Var(&opts.containerLabels, flagContainerLabel, "Container labels")
  29. flags.VarP(&opts.env, flagEnv, "e", "Set environment variables")
  30. flags.Var(&opts.mounts, flagMount, "Attach a mount to the service")
  31. flags.StringSliceVar(&opts.constraints, flagConstraint, []string{}, "Placement constraints")
  32. flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments")
  33. flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port")
  34. flags.SetInterspersed(false)
  35. return cmd
  36. }
  37. func runCreate(dockerCli *client.DockerCli, opts *serviceOptions) error {
  38. apiClient := dockerCli.Client()
  39. createOpts := types.ServiceCreateOptions{}
  40. service, err := opts.ToService()
  41. if err != nil {
  42. return err
  43. }
  44. ctx := context.Background()
  45. // only send auth if flag was set
  46. if opts.registryAuth {
  47. // Retrieve encoded auth token from the image reference
  48. encodedAuth, err := dockerCli.RetrieveAuthTokenFromImage(ctx, opts.image)
  49. if err != nil {
  50. return err
  51. }
  52. createOpts.EncodedRegistryAuth = encodedAuth
  53. }
  54. response, err := apiClient.ServiceCreate(ctx, service, createOpts)
  55. if err != nil {
  56. return err
  57. }
  58. fmt.Fprintf(dockerCli.Out(), "%s\n", response.ID)
  59. return nil
  60. }