create.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package service
  2. import (
  3. "fmt"
  4. "github.com/docker/docker/api/types"
  5. "github.com/docker/docker/cli"
  6. "github.com/docker/docker/cli/command"
  7. "github.com/spf13/cobra"
  8. "golang.org/x/net/context"
  9. )
  10. func newCreateCommand(dockerCli *command.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. flags.StringVar(&opts.name, flagName, "", "Service name")
  27. addServiceFlags(cmd, opts)
  28. flags.VarP(&opts.labels, flagLabel, "l", "Service labels")
  29. flags.Var(&opts.containerLabels, flagContainerLabel, "Container labels")
  30. flags.VarP(&opts.env, flagEnv, "e", "Set environment variables")
  31. flags.Var(&opts.envFile, flagEnvFile, "Read in a file of environment variables")
  32. flags.Var(&opts.mounts, flagMount, "Attach a mount to the service")
  33. flags.StringSliceVar(&opts.constraints, flagConstraint, []string{}, "Placement constraints")
  34. flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments")
  35. flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port")
  36. flags.SetInterspersed(false)
  37. return cmd
  38. }
  39. func runCreate(dockerCli *command.DockerCli, opts *serviceOptions) error {
  40. apiClient := dockerCli.Client()
  41. createOpts := types.ServiceCreateOptions{}
  42. service, err := opts.ToService()
  43. if err != nil {
  44. return err
  45. }
  46. ctx := context.Background()
  47. // only send auth if flag was set
  48. if opts.registryAuth {
  49. // Retrieve encoded auth token from the image reference
  50. encodedAuth, err := command.RetrieveAuthTokenFromImage(ctx, dockerCli, opts.image)
  51. if err != nil {
  52. return err
  53. }
  54. createOpts.EncodedRegistryAuth = encodedAuth
  55. }
  56. response, err := apiClient.ServiceCreate(ctx, service, createOpts)
  57. if err != nil {
  58. return err
  59. }
  60. fmt.Fprintf(dockerCli.Out(), "%s\n", response.ID)
  61. return nil
  62. }