create.go 5.8 KB

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