backend.go 6.4 KB

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