create.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.mounts, flagMount, "Attach a mount to the service")
  32. flags.StringSliceVar(&opts.constraints, flagConstraint, []string{}, "Placement constraints")
  33. flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments")
  34. flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port")
  35. flags.SetInterspersed(false)
  36. return cmd
  37. }
  38. func runCreate(dockerCli *command.DockerCli, opts *serviceOptions) error {
  39. apiClient := dockerCli.Client()
  40. createOpts := types.ServiceCreateOptions{}
  41. service, err := opts.ToService()
  42. if err != nil {
  43. return err
  44. }
  45. ctx := context.Background()
  46. // only send auth if flag was set
  47. if opts.registryAuth {
  48. // Retrieve encoded auth token from the image reference
  49. encodedAuth, err := command.RetrieveAuthTokenFromImage(ctx, dockerCli, opts.image)
  50. if err != nil {
  51. return err
  52. }
  53. createOpts.EncodedRegistryAuth = encodedAuth
  54. }
  55. response, err := apiClient.ServiceCreate(ctx, service, createOpts)
  56. if err != nil {
  57. return err
  58. }
  59. fmt.Fprintf(dockerCli.Out(), "%s\n", response.ID)
  60. return nil
  61. }