backend.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // +build local
  2. /*
  3. Copyright 2020 Docker, Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package local
  15. import (
  16. "bufio"
  17. "context"
  18. "io"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/go-connections/nat"
  24. "github.com/docker/docker/api/types"
  25. "github.com/docker/docker/api/types/container"
  26. "github.com/docker/docker/client"
  27. "github.com/docker/docker/pkg/stdcopy"
  28. "github.com/pkg/errors"
  29. "github.com/docker/api/backend"
  30. "github.com/docker/api/compose"
  31. "github.com/docker/api/containers"
  32. "github.com/docker/api/context/cloud"
  33. "github.com/docker/api/errdefs"
  34. )
  35. type local struct {
  36. apiClient *client.Client
  37. }
  38. func init() {
  39. backend.Register("local", "local", service, cloud.NotImplementedCloudService)
  40. }
  41. func service(ctx context.Context) (backend.Service, error) {
  42. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &local{
  47. apiClient,
  48. }, nil
  49. }
  50. func (ms *local) ContainerService() containers.Service {
  51. return ms
  52. }
  53. func (ms *local) ComposeService() compose.Service {
  54. return nil
  55. }
  56. func (ms *local) Inspect(ctx context.Context, id string) (containers.Container, error) {
  57. c, err := ms.apiClient.ContainerInspect(ctx, id)
  58. if err != nil {
  59. return containers.Container{}, err
  60. }
  61. status := ""
  62. if c.State != nil {
  63. status = c.State.Status
  64. }
  65. command := ""
  66. if c.Config != nil &&
  67. c.Config.Cmd != nil {
  68. command = strings.Join(c.Config.Cmd, " ")
  69. }
  70. return containers.Container{
  71. ID: stringid.TruncateID(c.ID),
  72. Status: status,
  73. Image: c.Image,
  74. Command: command,
  75. Platform: c.Platform,
  76. }, nil
  77. }
  78. func (ms *local) List(ctx context.Context, all bool) ([]containers.Container, error) {
  79. css, err := ms.apiClient.ContainerList(ctx, types.ContainerListOptions{
  80. All: all,
  81. })
  82. if err != nil {
  83. return []containers.Container{}, err
  84. }
  85. var result []containers.Container
  86. for _, container := range css {
  87. result = append(result, containers.Container{
  88. ID: stringid.TruncateID(container.ID),
  89. Image: container.Image,
  90. // TODO: `Status` is a human readable string ("Up 24 minutes"),
  91. // we need to return the `State` instead but first we need to
  92. // define an enum on the proto side with all the possible container
  93. // statuses. We also need to add a `Created` property on the gRPC side.
  94. Status: container.Status,
  95. Command: container.Command,
  96. Ports: toPorts(container.Ports),
  97. })
  98. }
  99. return result, nil
  100. }
  101. func (ms *local) Run(ctx context.Context, r containers.ContainerConfig) error {
  102. exposedPorts, hostBindings, err := fromPorts(r.Ports)
  103. if err != nil {
  104. return err
  105. }
  106. containerConfig := &container.Config{
  107. Image: r.Image,
  108. Labels: r.Labels,
  109. ExposedPorts: exposedPorts,
  110. }
  111. hostConfig := &container.HostConfig{
  112. PortBindings: hostBindings,
  113. }
  114. created, err := ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  115. if err != nil {
  116. if client.IsErrNotFound(err) {
  117. io, err := ms.apiClient.ImagePull(ctx, r.Image, types.ImagePullOptions{})
  118. if err != nil {
  119. return err
  120. }
  121. scanner := bufio.NewScanner(io)
  122. // Read the whole body, otherwise the pulling stops
  123. for scanner.Scan() {
  124. }
  125. if err = scanner.Err(); err != nil {
  126. return err
  127. }
  128. if err = io.Close(); err != nil {
  129. return err
  130. }
  131. created, err = ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  132. if err != nil {
  133. return err
  134. }
  135. } else {
  136. return err
  137. }
  138. }
  139. return ms.apiClient.ContainerStart(ctx, created.ID, types.ContainerStartOptions{})
  140. }
  141. func (ms *local) Start(ctx context.Context, containerID string) error {
  142. return ms.apiClient.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
  143. }
  144. func (ms *local) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  145. var t *time.Duration
  146. if timeout != nil {
  147. timeoutValue := time.Duration(*timeout) * time.Second
  148. t = &timeoutValue
  149. }
  150. return ms.apiClient.ContainerStop(ctx, containerID, t)
  151. }
  152. func (ms *local) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  153. cec, err := ms.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  154. Cmd: []string{request.Command},
  155. Tty: true,
  156. AttachStdin: true,
  157. AttachStdout: true,
  158. AttachStderr: true,
  159. })
  160. if err != nil {
  161. return err
  162. }
  163. resp, err := ms.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  164. Tty: true,
  165. })
  166. if err != nil {
  167. return err
  168. }
  169. defer resp.Close()
  170. readChannel := make(chan error, 10)
  171. writeChannel := make(chan error, 10)
  172. go func() {
  173. _, err := io.Copy(request.Stdout, resp.Reader)
  174. readChannel <- err
  175. }()
  176. go func() {
  177. _, err := io.Copy(resp.Conn, request.Stdin)
  178. writeChannel <- err
  179. }()
  180. for {
  181. select {
  182. case err := <-readChannel:
  183. return err
  184. case err := <-writeChannel:
  185. return err
  186. }
  187. }
  188. }
  189. func (ms *local) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  190. c, err := ms.apiClient.ContainerInspect(ctx, containerName)
  191. if err != nil {
  192. return err
  193. }
  194. r, err := ms.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  195. ShowStdout: true,
  196. ShowStderr: true,
  197. Follow: request.Follow,
  198. })
  199. if err != nil {
  200. return err
  201. }
  202. // nolint errcheck
  203. defer r.Close()
  204. if c.Config.Tty {
  205. _, err = io.Copy(request.Writer, r)
  206. } else {
  207. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  208. }
  209. return err
  210. }
  211. func (ms *local) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  212. err := ms.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  213. Force: request.Force,
  214. })
  215. if client.IsErrNotFound(err) {
  216. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  217. }
  218. return err
  219. }
  220. func toPorts(ports []types.Port) []containers.Port {
  221. result := []containers.Port{}
  222. for _, port := range ports {
  223. result = append(result, containers.Port{
  224. ContainerPort: uint32(port.PrivatePort),
  225. HostPort: uint32(port.PublicPort),
  226. HostIP: port.IP,
  227. Protocol: port.Type,
  228. })
  229. }
  230. return result
  231. }
  232. func fromPorts(ports []containers.Port) (map[nat.Port]struct{}, map[nat.Port][]nat.PortBinding, error) {
  233. var (
  234. exposedPorts = make(map[nat.Port]struct{}, len(ports))
  235. bindings = make(map[nat.Port][]nat.PortBinding)
  236. )
  237. for _, port := range ports {
  238. p, err := nat.NewPort(port.Protocol, strconv.Itoa(int(port.ContainerPort)))
  239. if err != nil {
  240. return nil, nil, err
  241. }
  242. if _, exists := exposedPorts[p]; !exists {
  243. exposedPorts[p] = struct{}{}
  244. }
  245. portBinding := nat.PortBinding{
  246. HostIP: port.HostIP,
  247. HostPort: strconv.Itoa(int(port.HostPort)),
  248. }
  249. bslice, exists := bindings[p]
  250. if !exists {
  251. bslice = []nat.PortBinding{}
  252. }
  253. bindings[p] = append(bslice, portBinding)
  254. }
  255. return exposedPorts, bindings, nil
  256. }