container_routes.go 21 KB

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