create.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/container"
  8. networktypes "github.com/docker/docker/api/types/network"
  9. "github.com/docker/docker/cli"
  10. "github.com/docker/docker/cli/command"
  11. "github.com/docker/docker/cli/command/image"
  12. apiclient "github.com/docker/docker/client"
  13. "github.com/docker/docker/pkg/jsonmessage"
  14. // FIXME migrate to docker/distribution/reference
  15. "github.com/docker/docker/reference"
  16. "github.com/docker/docker/registry"
  17. "github.com/spf13/cobra"
  18. "github.com/spf13/pflag"
  19. "golang.org/x/net/context"
  20. )
  21. type createOptions struct {
  22. name string
  23. }
  24. // NewCreateCommand creates a new cobra.Command for `docker create`
  25. func NewCreateCommand(dockerCli *command.DockerCli) *cobra.Command {
  26. var opts createOptions
  27. var copts *containerOptions
  28. cmd := &cobra.Command{
  29. Use: "create [OPTIONS] IMAGE [COMMAND] [ARG...]",
  30. Short: "Create a new container",
  31. Args: cli.RequiresMinArgs(1),
  32. RunE: func(cmd *cobra.Command, args []string) error {
  33. copts.Image = args[0]
  34. if len(args) > 1 {
  35. copts.Args = args[1:]
  36. }
  37. return runCreate(dockerCli, cmd.Flags(), &opts, copts)
  38. },
  39. }
  40. flags := cmd.Flags()
  41. flags.SetInterspersed(false)
  42. flags.StringVar(&opts.name, "name", "", "Assign a name to the container")
  43. // Add an explicit help that doesn't have a `-h` to prevent the conflict
  44. // with hostname
  45. flags.Bool("help", false, "Print usage")
  46. command.AddTrustedFlags(flags, true)
  47. copts = addFlags(flags)
  48. return cmd
  49. }
  50. func runCreate(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts *createOptions, copts *containerOptions) error {
  51. config, hostConfig, networkingConfig, err := parse(flags, copts)
  52. if err != nil {
  53. reportError(dockerCli.Err(), "create", err.Error(), true)
  54. return cli.StatusError{StatusCode: 125}
  55. }
  56. response, err := createContainer(context.Background(), dockerCli, config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, opts.name)
  57. if err != nil {
  58. return err
  59. }
  60. fmt.Fprintln(dockerCli.Out(), response.ID)
  61. return nil
  62. }
  63. func pullImage(ctx context.Context, dockerCli *command.DockerCli, image string, out io.Writer) error {
  64. ref, err := reference.ParseNamed(image)
  65. if err != nil {
  66. return err
  67. }
  68. // Resolve the Repository name from fqn to RepositoryInfo
  69. repoInfo, err := registry.ParseRepositoryInfo(ref)
  70. if err != nil {
  71. return err
  72. }
  73. authConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index)
  74. encodedAuth, err := command.EncodeAuthToBase64(authConfig)
  75. if err != nil {
  76. return err
  77. }
  78. options := types.ImageCreateOptions{
  79. RegistryAuth: encodedAuth,
  80. }
  81. responseBody, err := dockerCli.Client().ImageCreate(ctx, image, options)
  82. if err != nil {
  83. return err
  84. }
  85. defer responseBody.Close()
  86. return jsonmessage.DisplayJSONMessagesStream(
  87. responseBody,
  88. out,
  89. dockerCli.Out().FD(),
  90. dockerCli.Out().IsTerminal(),
  91. nil)
  92. }
  93. type cidFile struct {
  94. path string
  95. file *os.File
  96. written bool
  97. }
  98. func (cid *cidFile) Close() error {
  99. cid.file.Close()
  100. if cid.written {
  101. return nil
  102. }
  103. if err := os.Remove(cid.path); err != nil {
  104. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  105. }
  106. return nil
  107. }
  108. func (cid *cidFile) Write(id string) error {
  109. if _, err := cid.file.Write([]byte(id)); err != nil {
  110. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  111. }
  112. cid.written = true
  113. return nil
  114. }
  115. func newCIDFile(path string) (*cidFile, error) {
  116. if _, err := os.Stat(path); err == nil {
  117. return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
  118. }
  119. f, err := os.Create(path)
  120. if err != nil {
  121. return nil, fmt.Errorf("Failed to create the container ID file: %s", err)
  122. }
  123. return &cidFile{path: path, file: f}, nil
  124. }
  125. func createContainer(ctx context.Context, dockerCli *command.DockerCli, config *container.Config, hostConfig *container.HostConfig, networkingConfig *networktypes.NetworkingConfig, cidfile, name string) (*container.ContainerCreateCreatedBody, error) {
  126. stderr := dockerCli.Err()
  127. var containerIDFile *cidFile
  128. if cidfile != "" {
  129. var err error
  130. if containerIDFile, err = newCIDFile(cidfile); err != nil {
  131. return nil, err
  132. }
  133. defer containerIDFile.Close()
  134. }
  135. var trustedRef reference.Canonical
  136. _, ref, err := reference.ParseIDOrReference(config.Image)
  137. if err != nil {
  138. return nil, err
  139. }
  140. if ref != nil {
  141. ref = reference.WithDefaultTag(ref)
  142. if ref, ok := ref.(reference.NamedTagged); ok && command.IsTrusted() {
  143. var err error
  144. trustedRef, err = image.TrustedReference(ctx, dockerCli, ref, nil)
  145. if err != nil {
  146. return nil, err
  147. }
  148. config.Image = trustedRef.String()
  149. }
  150. }
  151. //create the container
  152. response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, name)
  153. //if image not found try to pull it
  154. if err != nil {
  155. if apiclient.IsErrImageNotFound(err) && ref != nil {
  156. fmt.Fprintf(stderr, "Unable to find image '%s' locally\n", ref.String())
  157. // we don't want to write to stdout anything apart from container.ID
  158. if err = pullImage(ctx, dockerCli, config.Image, stderr); err != nil {
  159. return nil, err
  160. }
  161. if ref, ok := ref.(reference.NamedTagged); ok && trustedRef != nil {
  162. if err := image.TagTrusted(ctx, dockerCli, trustedRef, ref); err != nil {
  163. return nil, err
  164. }
  165. }
  166. // Retry
  167. var retryErr error
  168. response, retryErr = dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, name)
  169. if retryErr != nil {
  170. return nil, retryErr
  171. }
  172. } else {
  173. return nil, err
  174. }
  175. }
  176. for _, warning := range response.Warnings {
  177. fmt.Fprintf(stderr, "WARNING: %s\n", warning)
  178. }
  179. if containerIDFile != nil {
  180. if err = containerIDFile.Write(response.ID); err != nil {
  181. return nil, err
  182. }
  183. }
  184. return &response, nil
  185. }