backend.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. }, nil
  76. }
  77. func (ms *local) List(ctx context.Context, all bool) ([]containers.Container, error) {
  78. css, err := ms.apiClient.ContainerList(ctx, types.ContainerListOptions{
  79. All: all,
  80. })
  81. if err != nil {
  82. return []containers.Container{}, err
  83. }
  84. var result []containers.Container
  85. for _, container := range css {
  86. result = append(result, containers.Container{
  87. ID: stringid.TruncateID(container.ID),
  88. Image: container.Image,
  89. // TODO: `Status` is a human readable string ("Up 24 minutes"),
  90. // we need to return the `State` instead but first we need to
  91. // define an enum on the proto side with all the possible container
  92. // statuses. We also need to add a `Created` property on the gRPC side.
  93. Status: container.Status,
  94. Command: container.Command,
  95. Ports: toPorts(container.Ports),
  96. })
  97. }
  98. return result, nil
  99. }
  100. func (ms *local) Run(ctx context.Context, r containers.ContainerConfig) error {
  101. exposedPorts, hostBindings, err := fromPorts(r.Ports)
  102. if err != nil {
  103. return err
  104. }
  105. containerConfig := &container.Config{
  106. Image: r.Image,
  107. Labels: r.Labels,
  108. ExposedPorts: exposedPorts,
  109. }
  110. hostConfig := &container.HostConfig{
  111. PortBindings: hostBindings,
  112. }
  113. created, err := ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  114. if err != nil {
  115. if client.IsErrNotFound(err) {
  116. io, err := ms.apiClient.ImagePull(ctx, r.Image, types.ImagePullOptions{})
  117. if err != nil {
  118. return err
  119. }
  120. scanner := bufio.NewScanner(io)
  121. // Read the whole body, otherwise the pulling stops
  122. for scanner.Scan() {
  123. }
  124. if err = scanner.Err(); err != nil {
  125. return err
  126. }
  127. if err = io.Close(); err != nil {
  128. return err
  129. }
  130. created, err = ms.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, r.ID)
  131. if err != nil {
  132. return err
  133. }
  134. } else {
  135. return err
  136. }
  137. }
  138. return ms.apiClient.ContainerStart(ctx, created.ID, types.ContainerStartOptions{})
  139. }
  140. func (ms *local) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  141. var t *time.Duration
  142. if timeout != nil {
  143. timeoutValue := time.Duration(*timeout) * time.Second
  144. t = &timeoutValue
  145. }
  146. return ms.apiClient.ContainerStop(ctx, containerID, t)
  147. }
  148. func (ms *local) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  149. cec, err := ms.apiClient.ContainerExecCreate(ctx, name, types.ExecConfig{
  150. Cmd: []string{command},
  151. Tty: true,
  152. AttachStdin: true,
  153. AttachStdout: true,
  154. AttachStderr: true,
  155. })
  156. if err != nil {
  157. return err
  158. }
  159. resp, err := ms.apiClient.ContainerExecAttach(ctx, cec.ID, types.ExecStartCheck{
  160. Tty: true,
  161. })
  162. if err != nil {
  163. return err
  164. }
  165. defer resp.Close()
  166. readChannel := make(chan error, 10)
  167. writeChannel := make(chan error, 10)
  168. go func() {
  169. _, err := io.Copy(writer, resp.Reader)
  170. readChannel <- err
  171. }()
  172. go func() {
  173. _, err := io.Copy(resp.Conn, reader)
  174. writeChannel <- err
  175. }()
  176. for {
  177. select {
  178. case err := <-readChannel:
  179. return err
  180. case err := <-writeChannel:
  181. return err
  182. }
  183. }
  184. }
  185. func (ms *local) Logs(ctx context.Context, containerName string, request containers.LogsRequest) error {
  186. c, err := ms.apiClient.ContainerInspect(ctx, containerName)
  187. if err != nil {
  188. return err
  189. }
  190. r, err := ms.apiClient.ContainerLogs(ctx, containerName, types.ContainerLogsOptions{
  191. ShowStdout: true,
  192. ShowStderr: true,
  193. Follow: request.Follow,
  194. })
  195. if err != nil {
  196. return err
  197. }
  198. // nolint errcheck
  199. defer r.Close()
  200. if c.Config.Tty {
  201. _, err = io.Copy(request.Writer, r)
  202. } else {
  203. _, err = stdcopy.StdCopy(request.Writer, request.Writer, r)
  204. }
  205. return err
  206. }
  207. func (ms *local) Delete(ctx context.Context, containerID string, force bool) error {
  208. err := ms.apiClient.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
  209. Force: force,
  210. })
  211. if client.IsErrNotFound(err) {
  212. return errors.Wrapf(errdefs.ErrNotFound, "container %q", containerID)
  213. }
  214. return err
  215. }
  216. func toPorts(ports []types.Port) []containers.Port {
  217. result := []containers.Port{}
  218. for _, port := range ports {
  219. result = append(result, containers.Port{
  220. ContainerPort: uint32(port.PrivatePort),
  221. HostPort: uint32(port.PublicPort),
  222. HostIP: port.IP,
  223. Protocol: port.Type,
  224. })
  225. }
  226. return result
  227. }
  228. func fromPorts(ports []containers.Port) (map[nat.Port]struct{}, map[nat.Port][]nat.PortBinding, error) {
  229. var (
  230. exposedPorts = make(map[nat.Port]struct{}, len(ports))
  231. bindings = make(map[nat.Port][]nat.PortBinding)
  232. )
  233. for _, port := range ports {
  234. p, err := nat.NewPort(port.Protocol, strconv.Itoa(int(port.ContainerPort)))
  235. if err != nil {
  236. return nil, nil, err
  237. }
  238. if _, exists := exposedPorts[p]; !exists {
  239. exposedPorts[p] = struct{}{}
  240. }
  241. portBinding := nat.PortBinding{
  242. HostIP: port.HostIP,
  243. HostPort: strconv.Itoa(int(port.HostPort)),
  244. }
  245. bslice, exists := bindings[p]
  246. if !exists {
  247. bslice = []nat.PortBinding{}
  248. }
  249. bindings[p] = append(bslice, portBinding)
  250. }
  251. return exposedPorts, bindings, nil
  252. }