container_routes.go 21 KB

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