container_routes.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. package container // import "github.com/docker/docker/api/server/router/container"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "github.com/containerd/containerd/platforms"
  10. "github.com/docker/docker/api/server/httpstatus"
  11. "github.com/docker/docker/api/server/httputils"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/backend"
  14. "github.com/docker/docker/api/types/container"
  15. "github.com/docker/docker/api/types/filters"
  16. "github.com/docker/docker/api/types/versions"
  17. containerpkg "github.com/docker/docker/container"
  18. "github.com/docker/docker/errdefs"
  19. "github.com/docker/docker/pkg/ioutils"
  20. "github.com/moby/sys/signal"
  21. specs "github.com/opencontainers/image-spec/specs-go/v1"
  22. "github.com/pkg/errors"
  23. "github.com/sirupsen/logrus"
  24. "golang.org/x/net/websocket"
  25. )
  26. func (s *containerRouter) postCommit(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  27. if err := httputils.ParseForm(r); err != nil {
  28. return err
  29. }
  30. if err := httputils.CheckForJSON(r); err != nil {
  31. return err
  32. }
  33. // TODO: remove pause arg, and always pause in backend
  34. pause := httputils.BoolValue(r, "pause")
  35. version := httputils.VersionFromContext(ctx)
  36. if r.FormValue("pause") == "" && versions.GreaterThanOrEqualTo(version, "1.13") {
  37. pause = true
  38. }
  39. config, _, _, err := s.decoder.DecodeConfig(r.Body)
  40. if err != nil && err != io.EOF { // Do not fail if body is empty.
  41. return err
  42. }
  43. commitCfg := &backend.CreateImageConfig{
  44. Pause: pause,
  45. Repo: r.Form.Get("repo"),
  46. Tag: r.Form.Get("tag"),
  47. Author: r.Form.Get("author"),
  48. Comment: r.Form.Get("comment"),
  49. Config: config,
  50. Changes: r.Form["changes"],
  51. }
  52. imgID, err := s.backend.CreateImageFromContainer(r.Form.Get("container"), commitCfg)
  53. if err != nil {
  54. return err
  55. }
  56. return httputils.WriteJSON(w, http.StatusCreated, &types.IDResponse{ID: imgID})
  57. }
  58. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  59. if err := httputils.ParseForm(r); err != nil {
  60. return err
  61. }
  62. filter, err := filters.FromJSON(r.Form.Get("filters"))
  63. if err != nil {
  64. return err
  65. }
  66. config := &types.ContainerListOptions{
  67. All: httputils.BoolValue(r, "all"),
  68. Size: httputils.BoolValue(r, "size"),
  69. Since: r.Form.Get("since"),
  70. Before: r.Form.Get("before"),
  71. Filters: filter,
  72. }
  73. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  74. limit, err := strconv.Atoi(tmpLimit)
  75. if err != nil {
  76. return err
  77. }
  78. config.Limit = limit
  79. }
  80. containers, err := s.backend.Containers(config)
  81. if err != nil {
  82. return err
  83. }
  84. return httputils.WriteJSON(w, http.StatusOK, containers)
  85. }
  86. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  87. if err := httputils.ParseForm(r); err != nil {
  88. return err
  89. }
  90. stream := httputils.BoolValueOrDefault(r, "stream", true)
  91. if !stream {
  92. w.Header().Set("Content-Type", "application/json")
  93. }
  94. var oneShot bool
  95. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.41") {
  96. oneShot = httputils.BoolValueOrDefault(r, "one-shot", false)
  97. }
  98. config := &backend.ContainerStatsConfig{
  99. Stream: stream,
  100. OneShot: oneShot,
  101. OutStream: w,
  102. Version: httputils.VersionFromContext(ctx),
  103. }
  104. return s.backend.ContainerStats(ctx, vars["name"], config)
  105. }
  106. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  107. if err := httputils.ParseForm(r); err != nil {
  108. return err
  109. }
  110. // Args are validated before the stream starts because when it starts we're
  111. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  112. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  113. // any error after the stream starts (i.e. container not found, wrong parameters)
  114. // with the appropriate status code.
  115. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  116. if !(stdout || stderr) {
  117. return errdefs.InvalidParameter(errors.New("Bad parameters: you must choose at least one stream"))
  118. }
  119. containerName := vars["name"]
  120. logsConfig := &types.ContainerLogsOptions{
  121. Follow: httputils.BoolValue(r, "follow"),
  122. Timestamps: httputils.BoolValue(r, "timestamps"),
  123. Since: r.Form.Get("since"),
  124. Until: r.Form.Get("until"),
  125. Tail: r.Form.Get("tail"),
  126. ShowStdout: stdout,
  127. ShowStderr: stderr,
  128. Details: httputils.BoolValue(r, "details"),
  129. }
  130. msgs, tty, err := s.backend.ContainerLogs(ctx, containerName, logsConfig)
  131. if err != nil {
  132. return err
  133. }
  134. // if has a tty, we're not muxing streams. if it doesn't, we are. simple.
  135. // this is the point of no return for writing a response. once we call
  136. // WriteLogStream, the response has been started and errors will be
  137. // returned in band by WriteLogStream
  138. httputils.WriteLogStream(ctx, w, msgs, logsConfig, !tty)
  139. return nil
  140. }
  141. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  142. return s.backend.ContainerExport(vars["name"], w)
  143. }
  144. type bodyOnStartError struct{}
  145. func (bodyOnStartError) Error() string {
  146. return "starting container with non-empty request body was deprecated since API v1.22 and removed in v1.24"
  147. }
  148. func (bodyOnStartError) InvalidParameter() {}
  149. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  150. // If contentLength is -1, we can assumed chunked encoding
  151. // or more technically that the length is unknown
  152. // https://golang.org/src/pkg/net/http/request.go#L139
  153. // net/http otherwise seems to swallow any headers related to chunked encoding
  154. // including r.TransferEncoding
  155. // allow a nil body for backwards compatibility
  156. version := httputils.VersionFromContext(ctx)
  157. var hostConfig *container.HostConfig
  158. // A non-nil json object is at least 7 characters.
  159. if r.ContentLength > 7 || r.ContentLength == -1 {
  160. if versions.GreaterThanOrEqualTo(version, "1.24") {
  161. return bodyOnStartError{}
  162. }
  163. if err := httputils.CheckForJSON(r); err != nil {
  164. return err
  165. }
  166. c, err := s.decoder.DecodeHostConfig(r.Body)
  167. if err != nil {
  168. return err
  169. }
  170. hostConfig = c
  171. }
  172. if err := httputils.ParseForm(r); err != nil {
  173. return err
  174. }
  175. checkpoint := r.Form.Get("checkpoint")
  176. checkpointDir := r.Form.Get("checkpoint-dir")
  177. if err := s.backend.ContainerStart(vars["name"], hostConfig, checkpoint, checkpointDir); err != nil {
  178. return err
  179. }
  180. w.WriteHeader(http.StatusNoContent)
  181. return nil
  182. }
  183. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  184. if err := httputils.ParseForm(r); err != nil {
  185. return err
  186. }
  187. var (
  188. options container.StopOptions
  189. version = httputils.VersionFromContext(ctx)
  190. )
  191. if versions.GreaterThanOrEqualTo(version, "1.42") {
  192. if sig := r.Form.Get("signal"); sig != "" {
  193. if _, err := signal.ParseSignal(sig); err != nil {
  194. return errdefs.InvalidParameter(err)
  195. }
  196. options.Signal = sig
  197. }
  198. }
  199. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  200. valSeconds, err := strconv.Atoi(tmpSeconds)
  201. if err != nil {
  202. return err
  203. }
  204. options.Timeout = &valSeconds
  205. }
  206. if err := s.backend.ContainerStop(ctx, vars["name"], options); err != nil {
  207. return err
  208. }
  209. w.WriteHeader(http.StatusNoContent)
  210. return nil
  211. }
  212. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  213. if err := httputils.ParseForm(r); err != nil {
  214. return err
  215. }
  216. name := vars["name"]
  217. if err := s.backend.ContainerKill(name, r.Form.Get("signal")); err != nil {
  218. var isStopped bool
  219. if errdefs.IsConflict(err) {
  220. isStopped = true
  221. }
  222. // Return error that's not caused because the container is stopped.
  223. // Return error if the container is not running and the api is >= 1.20
  224. // to keep backwards compatibility.
  225. version := httputils.VersionFromContext(ctx)
  226. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  227. return errors.Wrapf(err, "Cannot kill container: %s", name)
  228. }
  229. }
  230. w.WriteHeader(http.StatusNoContent)
  231. return nil
  232. }
  233. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  234. if err := httputils.ParseForm(r); err != nil {
  235. return err
  236. }
  237. var (
  238. options container.StopOptions
  239. version = httputils.VersionFromContext(ctx)
  240. )
  241. if versions.GreaterThanOrEqualTo(version, "1.42") {
  242. if sig := r.Form.Get("signal"); sig != "" {
  243. if _, err := signal.ParseSignal(sig); err != nil {
  244. return errdefs.InvalidParameter(err)
  245. }
  246. options.Signal = sig
  247. }
  248. }
  249. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  250. valSeconds, err := strconv.Atoi(tmpSeconds)
  251. if err != nil {
  252. return err
  253. }
  254. options.Timeout = &valSeconds
  255. }
  256. if err := s.backend.ContainerRestart(ctx, vars["name"], options); err != nil {
  257. return err
  258. }
  259. w.WriteHeader(http.StatusNoContent)
  260. return nil
  261. }
  262. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  263. if err := httputils.ParseForm(r); err != nil {
  264. return err
  265. }
  266. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  267. return err
  268. }
  269. w.WriteHeader(http.StatusNoContent)
  270. return nil
  271. }
  272. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  273. if err := httputils.ParseForm(r); err != nil {
  274. return err
  275. }
  276. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  277. return err
  278. }
  279. w.WriteHeader(http.StatusNoContent)
  280. return nil
  281. }
  282. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  283. // Behavior changed in version 1.30 to handle wait condition and to
  284. // return headers immediately.
  285. version := httputils.VersionFromContext(ctx)
  286. legacyBehaviorPre130 := versions.LessThan(version, "1.30")
  287. legacyRemovalWaitPre134 := false
  288. // The wait condition defaults to "not-running".
  289. waitCondition := containerpkg.WaitConditionNotRunning
  290. if !legacyBehaviorPre130 {
  291. if err := httputils.ParseForm(r); err != nil {
  292. return err
  293. }
  294. if v := r.Form.Get("condition"); v != "" {
  295. switch container.WaitCondition(v) {
  296. case container.WaitConditionNextExit:
  297. waitCondition = containerpkg.WaitConditionNextExit
  298. case container.WaitConditionRemoved:
  299. waitCondition = containerpkg.WaitConditionRemoved
  300. legacyRemovalWaitPre134 = versions.LessThan(version, "1.34")
  301. default:
  302. return errdefs.InvalidParameter(errors.Errorf("invalid condition: %q", v))
  303. }
  304. }
  305. }
  306. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  307. if err != nil {
  308. return err
  309. }
  310. w.Header().Set("Content-Type", "application/json")
  311. if !legacyBehaviorPre130 {
  312. // Write response header immediately.
  313. w.WriteHeader(http.StatusOK)
  314. if flusher, ok := w.(http.Flusher); ok {
  315. flusher.Flush()
  316. }
  317. }
  318. // Block on the result of the wait operation.
  319. status := <-waitC
  320. // With API < 1.34, wait on WaitConditionRemoved did not return
  321. // in case container removal failed. The only way to report an
  322. // error back to the client is to not write anything (i.e. send
  323. // an empty response which will be treated as an error).
  324. if legacyRemovalWaitPre134 && status.Err() != nil {
  325. return nil
  326. }
  327. var waitError *container.WaitExitError
  328. if status.Err() != nil {
  329. waitError = &container.WaitExitError{Message: status.Err().Error()}
  330. }
  331. return json.NewEncoder(w).Encode(&container.WaitResponse{
  332. StatusCode: int64(status.ExitCode()),
  333. Error: waitError,
  334. })
  335. }
  336. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  337. changes, err := s.backend.ContainerChanges(vars["name"])
  338. if err != nil {
  339. return err
  340. }
  341. return httputils.WriteJSON(w, http.StatusOK, changes)
  342. }
  343. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  344. if err := httputils.ParseForm(r); err != nil {
  345. return err
  346. }
  347. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  348. if err != nil {
  349. return err
  350. }
  351. return httputils.WriteJSON(w, http.StatusOK, procList)
  352. }
  353. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  354. if err := httputils.ParseForm(r); err != nil {
  355. return err
  356. }
  357. name := vars["name"]
  358. newName := r.Form.Get("name")
  359. if err := s.backend.ContainerRename(name, newName); err != nil {
  360. return err
  361. }
  362. w.WriteHeader(http.StatusNoContent)
  363. return nil
  364. }
  365. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  366. if err := httputils.ParseForm(r); err != nil {
  367. return err
  368. }
  369. var updateConfig container.UpdateConfig
  370. if err := httputils.ReadJSON(r, &updateConfig); err != nil {
  371. return err
  372. }
  373. if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") {
  374. updateConfig.PidsLimit = nil
  375. }
  376. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  377. // Ignore KernelMemory removed in API 1.42.
  378. updateConfig.KernelMemory = 0
  379. }
  380. if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 {
  381. // Both `0` and `-1` are accepted to set "unlimited" when updating.
  382. // Historically, any negative value was accepted, so treat them as
  383. // "unlimited" as well.
  384. var unlimited int64
  385. updateConfig.PidsLimit = &unlimited
  386. }
  387. hostConfig := &container.HostConfig{
  388. Resources: updateConfig.Resources,
  389. RestartPolicy: updateConfig.RestartPolicy,
  390. }
  391. name := vars["name"]
  392. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  393. if err != nil {
  394. return err
  395. }
  396. return httputils.WriteJSON(w, http.StatusOK, resp)
  397. }
  398. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  399. if err := httputils.ParseForm(r); err != nil {
  400. return err
  401. }
  402. if err := httputils.CheckForJSON(r); err != nil {
  403. return err
  404. }
  405. name := r.Form.Get("name")
  406. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  407. if err != nil {
  408. return err
  409. }
  410. version := httputils.VersionFromContext(ctx)
  411. adjustCPUShares := versions.LessThan(version, "1.19")
  412. // When using API 1.24 and under, the client is responsible for removing the container
  413. if hostConfig != nil && versions.LessThan(version, "1.25") {
  414. hostConfig.AutoRemove = false
  415. }
  416. if hostConfig != nil && versions.LessThan(version, "1.40") {
  417. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  418. for _, m := range hostConfig.Mounts {
  419. if bo := m.BindOptions; bo != nil {
  420. bo.NonRecursive = false
  421. }
  422. }
  423. // Ignore KernelMemoryTCP because it was added in API 1.40.
  424. hostConfig.KernelMemoryTCP = 0
  425. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  426. if hostConfig.IpcMode.IsEmpty() {
  427. hostConfig.IpcMode = container.IPCModeShareable
  428. }
  429. }
  430. if hostConfig != nil && versions.LessThan(version, "1.41") && !s.cgroup2 {
  431. // Older clients expect the default to be "host" on cgroup v1 hosts
  432. if hostConfig.CgroupnsMode.IsEmpty() {
  433. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  434. }
  435. }
  436. if hostConfig != nil && versions.GreaterThanOrEqualTo(version, "1.42") {
  437. // Ignore KernelMemory removed in API 1.42.
  438. hostConfig.KernelMemory = 0
  439. }
  440. var platform *specs.Platform
  441. if versions.GreaterThanOrEqualTo(version, "1.41") {
  442. if v := r.Form.Get("platform"); v != "" {
  443. p, err := platforms.Parse(v)
  444. if err != nil {
  445. return errdefs.InvalidParameter(err)
  446. }
  447. platform = &p
  448. }
  449. }
  450. if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  451. // Don't set a limit if either no limit was specified, or "unlimited" was
  452. // explicitly set.
  453. // Both `0` and `-1` are accepted as "unlimited", and historically any
  454. // negative value was accepted, so treat those as "unlimited" as well.
  455. hostConfig.PidsLimit = nil
  456. }
  457. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  458. Name: name,
  459. Config: config,
  460. HostConfig: hostConfig,
  461. NetworkingConfig: networkingConfig,
  462. AdjustCPUShares: adjustCPUShares,
  463. Platform: platform,
  464. })
  465. if err != nil {
  466. return err
  467. }
  468. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  469. }
  470. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  471. if err := httputils.ParseForm(r); err != nil {
  472. return err
  473. }
  474. name := vars["name"]
  475. config := &types.ContainerRmConfig{
  476. ForceRemove: httputils.BoolValue(r, "force"),
  477. RemoveVolume: httputils.BoolValue(r, "v"),
  478. RemoveLink: httputils.BoolValue(r, "link"),
  479. }
  480. if err := s.backend.ContainerRm(name, config); err != nil {
  481. return err
  482. }
  483. w.WriteHeader(http.StatusNoContent)
  484. return nil
  485. }
  486. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  487. if err := httputils.ParseForm(r); err != nil {
  488. return err
  489. }
  490. height, err := strconv.Atoi(r.Form.Get("h"))
  491. if err != nil {
  492. return errdefs.InvalidParameter(err)
  493. }
  494. width, err := strconv.Atoi(r.Form.Get("w"))
  495. if err != nil {
  496. return errdefs.InvalidParameter(err)
  497. }
  498. return s.backend.ContainerResize(vars["name"], height, width)
  499. }
  500. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  501. err := httputils.ParseForm(r)
  502. if err != nil {
  503. return err
  504. }
  505. containerName := vars["name"]
  506. _, upgrade := r.Header["Upgrade"]
  507. detachKeys := r.FormValue("detachKeys")
  508. hijacker, ok := w.(http.Hijacker)
  509. if !ok {
  510. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  511. }
  512. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  513. conn, _, err := hijacker.Hijack()
  514. if err != nil {
  515. return nil, nil, nil, err
  516. }
  517. // set raw mode
  518. conn.Write([]byte{})
  519. if upgrade {
  520. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  521. } else {
  522. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  523. }
  524. closer := func() error {
  525. httputils.CloseStreams(conn)
  526. return nil
  527. }
  528. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  529. }
  530. attachConfig := &backend.ContainerAttachConfig{
  531. GetStreams: setupStreams,
  532. UseStdin: httputils.BoolValue(r, "stdin"),
  533. UseStdout: httputils.BoolValue(r, "stdout"),
  534. UseStderr: httputils.BoolValue(r, "stderr"),
  535. Logs: httputils.BoolValue(r, "logs"),
  536. Stream: httputils.BoolValue(r, "stream"),
  537. DetachKeys: detachKeys,
  538. MuxStreams: true,
  539. }
  540. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  541. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  542. // Remember to close stream if error happens
  543. conn, _, errHijack := hijacker.Hijack()
  544. if errHijack == nil {
  545. statusCode := httpstatus.FromError(err)
  546. statusText := http.StatusText(statusCode)
  547. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n%s\r\n", statusCode, statusText, err.Error())
  548. httputils.CloseStreams(conn)
  549. } else {
  550. logrus.Errorf("Error Hijacking: %v", err)
  551. }
  552. }
  553. return nil
  554. }
  555. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  556. if err := httputils.ParseForm(r); err != nil {
  557. return err
  558. }
  559. containerName := vars["name"]
  560. var err error
  561. detachKeys := r.FormValue("detachKeys")
  562. done := make(chan struct{})
  563. started := make(chan struct{})
  564. version := httputils.VersionFromContext(ctx)
  565. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  566. wsChan := make(chan *websocket.Conn)
  567. h := func(conn *websocket.Conn) {
  568. wsChan <- conn
  569. <-done
  570. }
  571. srv := websocket.Server{Handler: h, Handshake: nil}
  572. go func() {
  573. close(started)
  574. srv.ServeHTTP(w, r)
  575. }()
  576. conn := <-wsChan
  577. // In case version 1.28 and above, a binary frame will be sent.
  578. // See 28176 for details.
  579. if versions.GreaterThanOrEqualTo(version, "1.28") {
  580. conn.PayloadType = websocket.BinaryFrame
  581. }
  582. return conn, conn, conn, nil
  583. }
  584. attachConfig := &backend.ContainerAttachConfig{
  585. GetStreams: setupStreams,
  586. Logs: httputils.BoolValue(r, "logs"),
  587. Stream: httputils.BoolValue(r, "stream"),
  588. DetachKeys: detachKeys,
  589. UseStdin: true,
  590. UseStdout: true,
  591. UseStderr: true,
  592. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  593. }
  594. err = s.backend.ContainerAttach(containerName, attachConfig)
  595. close(done)
  596. select {
  597. case <-started:
  598. if err != nil {
  599. logrus.Errorf("Error attaching websocket: %s", err)
  600. } else {
  601. logrus.Debug("websocket connection was closed by client")
  602. }
  603. return nil
  604. default:
  605. }
  606. return err
  607. }
  608. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  609. if err := httputils.ParseForm(r); err != nil {
  610. return err
  611. }
  612. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  613. if err != nil {
  614. return err
  615. }
  616. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  617. if err != nil {
  618. return err
  619. }
  620. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  621. }