container_routes.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. var updateConfig container.UpdateConfig
  357. if err := httputils.ReadJSON(r, &updateConfig); err != nil {
  358. return err
  359. }
  360. if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") {
  361. updateConfig.PidsLimit = nil
  362. }
  363. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  364. // Ignore KernelMemory removed in API 1.42.
  365. updateConfig.KernelMemory = 0
  366. }
  367. if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 {
  368. // Both `0` and `-1` are accepted to set "unlimited" when updating.
  369. // Historically, any negative value was accepted, so treat them as
  370. // "unlimited" as well.
  371. var unlimited int64
  372. updateConfig.PidsLimit = &unlimited
  373. }
  374. hostConfig := &container.HostConfig{
  375. Resources: updateConfig.Resources,
  376. RestartPolicy: updateConfig.RestartPolicy,
  377. }
  378. name := vars["name"]
  379. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  380. if err != nil {
  381. return err
  382. }
  383. return httputils.WriteJSON(w, http.StatusOK, resp)
  384. }
  385. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  386. if err := httputils.ParseForm(r); err != nil {
  387. return err
  388. }
  389. if err := httputils.CheckForJSON(r); err != nil {
  390. return err
  391. }
  392. name := r.Form.Get("name")
  393. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  394. if err != nil {
  395. return err
  396. }
  397. version := httputils.VersionFromContext(ctx)
  398. adjustCPUShares := versions.LessThan(version, "1.19")
  399. // When using API 1.24 and under, the client is responsible for removing the container
  400. if hostConfig != nil && versions.LessThan(version, "1.25") {
  401. hostConfig.AutoRemove = false
  402. }
  403. if hostConfig != nil && versions.LessThan(version, "1.40") {
  404. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  405. for _, m := range hostConfig.Mounts {
  406. if bo := m.BindOptions; bo != nil {
  407. bo.NonRecursive = false
  408. }
  409. }
  410. // Ignore KernelMemoryTCP because it was added in API 1.40.
  411. hostConfig.KernelMemoryTCP = 0
  412. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  413. if hostConfig.IpcMode.IsEmpty() {
  414. hostConfig.IpcMode = container.IPCModeShareable
  415. }
  416. }
  417. if hostConfig != nil && versions.LessThan(version, "1.41") && !s.cgroup2 {
  418. // Older clients expect the default to be "host" on cgroup v1 hosts
  419. if hostConfig.CgroupnsMode.IsEmpty() {
  420. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  421. }
  422. }
  423. if hostConfig != nil && versions.GreaterThanOrEqualTo(version, "1.42") {
  424. // Ignore KernelMemory removed in API 1.42.
  425. hostConfig.KernelMemory = 0
  426. }
  427. var platform *specs.Platform
  428. if versions.GreaterThanOrEqualTo(version, "1.41") {
  429. if v := r.Form.Get("platform"); v != "" {
  430. p, err := platforms.Parse(v)
  431. if err != nil {
  432. return errdefs.InvalidParameter(err)
  433. }
  434. platform = &p
  435. }
  436. }
  437. if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  438. // Don't set a limit if either no limit was specified, or "unlimited" was
  439. // explicitly set.
  440. // Both `0` and `-1` are accepted as "unlimited", and historically any
  441. // negative value was accepted, so treat those as "unlimited" as well.
  442. hostConfig.PidsLimit = nil
  443. }
  444. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  445. Name: name,
  446. Config: config,
  447. HostConfig: hostConfig,
  448. NetworkingConfig: networkingConfig,
  449. AdjustCPUShares: adjustCPUShares,
  450. Platform: platform,
  451. })
  452. if err != nil {
  453. return err
  454. }
  455. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  456. }
  457. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  458. if err := httputils.ParseForm(r); err != nil {
  459. return err
  460. }
  461. name := vars["name"]
  462. config := &types.ContainerRmConfig{
  463. ForceRemove: httputils.BoolValue(r, "force"),
  464. RemoveVolume: httputils.BoolValue(r, "v"),
  465. RemoveLink: httputils.BoolValue(r, "link"),
  466. }
  467. if err := s.backend.ContainerRm(name, config); err != nil {
  468. return err
  469. }
  470. w.WriteHeader(http.StatusNoContent)
  471. return nil
  472. }
  473. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  474. if err := httputils.ParseForm(r); err != nil {
  475. return err
  476. }
  477. height, err := strconv.Atoi(r.Form.Get("h"))
  478. if err != nil {
  479. return errdefs.InvalidParameter(err)
  480. }
  481. width, err := strconv.Atoi(r.Form.Get("w"))
  482. if err != nil {
  483. return errdefs.InvalidParameter(err)
  484. }
  485. return s.backend.ContainerResize(vars["name"], height, width)
  486. }
  487. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  488. err := httputils.ParseForm(r)
  489. if err != nil {
  490. return err
  491. }
  492. containerName := vars["name"]
  493. _, upgrade := r.Header["Upgrade"]
  494. detachKeys := r.FormValue("detachKeys")
  495. hijacker, ok := w.(http.Hijacker)
  496. if !ok {
  497. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  498. }
  499. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  500. conn, _, err := hijacker.Hijack()
  501. if err != nil {
  502. return nil, nil, nil, err
  503. }
  504. // set raw mode
  505. conn.Write([]byte{})
  506. if upgrade {
  507. 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")
  508. } else {
  509. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  510. }
  511. closer := func() error {
  512. httputils.CloseStreams(conn)
  513. return nil
  514. }
  515. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  516. }
  517. attachConfig := &backend.ContainerAttachConfig{
  518. GetStreams: setupStreams,
  519. UseStdin: httputils.BoolValue(r, "stdin"),
  520. UseStdout: httputils.BoolValue(r, "stdout"),
  521. UseStderr: httputils.BoolValue(r, "stderr"),
  522. Logs: httputils.BoolValue(r, "logs"),
  523. Stream: httputils.BoolValue(r, "stream"),
  524. DetachKeys: detachKeys,
  525. MuxStreams: true,
  526. }
  527. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  528. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  529. // Remember to close stream if error happens
  530. conn, _, errHijack := hijacker.Hijack()
  531. if errHijack == nil {
  532. statusCode := httpstatus.FromError(err)
  533. statusText := http.StatusText(statusCode)
  534. 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())
  535. httputils.CloseStreams(conn)
  536. } else {
  537. logrus.Errorf("Error Hijacking: %v", err)
  538. }
  539. }
  540. return nil
  541. }
  542. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  543. if err := httputils.ParseForm(r); err != nil {
  544. return err
  545. }
  546. containerName := vars["name"]
  547. var err error
  548. detachKeys := r.FormValue("detachKeys")
  549. done := make(chan struct{})
  550. started := make(chan struct{})
  551. version := httputils.VersionFromContext(ctx)
  552. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  553. wsChan := make(chan *websocket.Conn)
  554. h := func(conn *websocket.Conn) {
  555. wsChan <- conn
  556. <-done
  557. }
  558. srv := websocket.Server{Handler: h, Handshake: nil}
  559. go func() {
  560. close(started)
  561. srv.ServeHTTP(w, r)
  562. }()
  563. conn := <-wsChan
  564. // In case version 1.28 and above, a binary frame will be sent.
  565. // See 28176 for details.
  566. if versions.GreaterThanOrEqualTo(version, "1.28") {
  567. conn.PayloadType = websocket.BinaryFrame
  568. }
  569. return conn, conn, conn, nil
  570. }
  571. attachConfig := &backend.ContainerAttachConfig{
  572. GetStreams: setupStreams,
  573. Logs: httputils.BoolValue(r, "logs"),
  574. Stream: httputils.BoolValue(r, "stream"),
  575. DetachKeys: detachKeys,
  576. UseStdin: true,
  577. UseStdout: true,
  578. UseStderr: true,
  579. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  580. }
  581. err = s.backend.ContainerAttach(containerName, attachConfig)
  582. close(done)
  583. select {
  584. case <-started:
  585. if err != nil {
  586. logrus.Errorf("Error attaching websocket: %s", err)
  587. } else {
  588. logrus.Debug("websocket connection was closed by client")
  589. }
  590. return nil
  591. default:
  592. }
  593. return err
  594. }
  595. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  596. if err := httputils.ParseForm(r); err != nil {
  597. return err
  598. }
  599. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  600. if err != nil {
  601. return err
  602. }
  603. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  604. if err != nil {
  605. return err
  606. }
  607. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  608. }