podman
80 строк · 2.2 Кб
1package docker
2
3import (
4"context"
5"encoding/json"
6"errors"
7"net/http"
8"strings"
9)
10
11// ErrContainerAlreadyExists is the error returned by CreateContainer when the
12// container already exists.
13var ErrContainerAlreadyExists = errors.New("container already exists")
14
15// CreateContainerOptions specify parameters to the CreateContainer function.
16//
17// See https://goo.gl/tyzwVM for more details.
18type CreateContainerOptions struct {
19Name string
20Platform string
21Config *Config `qs:"-"`
22HostConfig *HostConfig `qs:"-"`
23NetworkingConfig *NetworkingConfig `qs:"-"`
24Context context.Context
25}
26
27// CreateContainer creates a new container, returning the container instance,
28// or an error in case of failure.
29//
30// The returned container instance contains only the container ID. To get more
31// details about the container after creating it, use InspectContainer.
32//
33// See https://goo.gl/tyzwVM for more details.
34func (c *Client) CreateContainer(opts CreateContainerOptions) (*Container, error) {
35path := "/containers/create?" + queryString(opts)
36resp, err := c.do(
37http.MethodPost,
38path,
39doOptions{
40data: struct {
41*Config
42HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty" toml:"HostConfig,omitempty"`
43NetworkingConfig *NetworkingConfig `json:"NetworkingConfig,omitempty" yaml:"NetworkingConfig,omitempty" toml:"NetworkingConfig,omitempty"`
44}{
45opts.Config,
46opts.HostConfig,
47opts.NetworkingConfig,
48},
49context: opts.Context,
50},
51)
52
53var e *Error
54if errors.As(err, &e) {
55if e.Status == http.StatusNotFound && strings.Contains(e.Message, "No such image") {
56return nil, ErrNoSuchImage
57}
58if e.Status == http.StatusConflict {
59return nil, ErrContainerAlreadyExists
60}
61// Workaround for 17.09 bug returning 400 instead of 409.
62// See https://github.com/moby/moby/issues/35021
63if e.Status == http.StatusBadRequest && strings.Contains(e.Message, "Conflict.") {
64return nil, ErrContainerAlreadyExists
65}
66}
67
68if err != nil {
69return nil, err
70}
71defer resp.Body.Close()
72var container Container
73if err := json.NewDecoder(resp.Body).Decode(&container); err != nil {
74return nil, err
75}
76
77container.Name = opts.Name
78
79return &container, nil
80}
81