container_routes.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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/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 seconds *int
  188. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  189. valSeconds, err := strconv.Atoi(tmpSeconds)
  190. if err != nil {
  191. return err
  192. }
  193. seconds = &valSeconds
  194. }
  195. if err := s.backend.ContainerStop(vars["name"], seconds); err != nil {
  196. return err
  197. }
  198. w.WriteHeader(http.StatusNoContent)
  199. return nil
  200. }
  201. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  202. if err := httputils.ParseForm(r); err != nil {
  203. return err
  204. }
  205. var sig syscall.Signal
  206. name := vars["name"]
  207. // If we have a signal, look at it. Otherwise, do nothing
  208. if sigStr := r.Form.Get("signal"); sigStr != "" {
  209. var err error
  210. if sig, err = signal.ParseSignal(sigStr); err != nil {
  211. return errdefs.InvalidParameter(err)
  212. }
  213. }
  214. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  215. var isStopped bool
  216. if errdefs.IsConflict(err) {
  217. isStopped = true
  218. }
  219. // Return error that's not caused because the container is stopped.
  220. // Return error if the container is not running and the api is >= 1.20
  221. // to keep backwards compatibility.
  222. version := httputils.VersionFromContext(ctx)
  223. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  224. return errors.Wrapf(err, "Cannot kill container: %s", name)
  225. }
  226. }
  227. w.WriteHeader(http.StatusNoContent)
  228. return nil
  229. }
  230. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  231. if err := httputils.ParseForm(r); err != nil {
  232. return err
  233. }
  234. var seconds *int
  235. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  236. valSeconds, err := strconv.Atoi(tmpSeconds)
  237. if err != nil {
  238. return err
  239. }
  240. seconds = &valSeconds
  241. }
  242. if err := s.backend.ContainerRestart(vars["name"], seconds); err != nil {
  243. return err
  244. }
  245. w.WriteHeader(http.StatusNoContent)
  246. return nil
  247. }
  248. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  249. if err := httputils.ParseForm(r); err != nil {
  250. return err
  251. }
  252. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  253. return err
  254. }
  255. w.WriteHeader(http.StatusNoContent)
  256. return nil
  257. }
  258. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  259. if err := httputils.ParseForm(r); err != nil {
  260. return err
  261. }
  262. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  263. return err
  264. }
  265. w.WriteHeader(http.StatusNoContent)
  266. return nil
  267. }
  268. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  269. // Behavior changed in version 1.30 to handle wait condition and to
  270. // return headers immediately.
  271. version := httputils.VersionFromContext(ctx)
  272. legacyBehaviorPre130 := versions.LessThan(version, "1.30")
  273. legacyRemovalWaitPre134 := false
  274. // The wait condition defaults to "not-running".
  275. waitCondition := containerpkg.WaitConditionNotRunning
  276. if !legacyBehaviorPre130 {
  277. if err := httputils.ParseForm(r); err != nil {
  278. return err
  279. }
  280. switch container.WaitCondition(r.Form.Get("condition")) {
  281. case container.WaitConditionNextExit:
  282. waitCondition = containerpkg.WaitConditionNextExit
  283. case container.WaitConditionRemoved:
  284. waitCondition = containerpkg.WaitConditionRemoved
  285. legacyRemovalWaitPre134 = versions.LessThan(version, "1.34")
  286. }
  287. }
  288. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  289. if err != nil {
  290. return err
  291. }
  292. w.Header().Set("Content-Type", "application/json")
  293. if !legacyBehaviorPre130 {
  294. // Write response header immediately.
  295. w.WriteHeader(http.StatusOK)
  296. if flusher, ok := w.(http.Flusher); ok {
  297. flusher.Flush()
  298. }
  299. }
  300. // Block on the result of the wait operation.
  301. status := <-waitC
  302. // With API < 1.34, wait on WaitConditionRemoved did not return
  303. // in case container removal failed. The only way to report an
  304. // error back to the client is to not write anything (i.e. send
  305. // an empty response which will be treated as an error).
  306. if legacyRemovalWaitPre134 && status.Err() != nil {
  307. return nil
  308. }
  309. var waitError *container.ContainerWaitOKBodyError
  310. if status.Err() != nil {
  311. waitError = &container.ContainerWaitOKBodyError{Message: status.Err().Error()}
  312. }
  313. return json.NewEncoder(w).Encode(&container.ContainerWaitOKBody{
  314. StatusCode: int64(status.ExitCode()),
  315. Error: waitError,
  316. })
  317. }
  318. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  319. changes, err := s.backend.ContainerChanges(vars["name"])
  320. if err != nil {
  321. return err
  322. }
  323. return httputils.WriteJSON(w, http.StatusOK, changes)
  324. }
  325. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  326. if err := httputils.ParseForm(r); err != nil {
  327. return err
  328. }
  329. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  330. if err != nil {
  331. return err
  332. }
  333. return httputils.WriteJSON(w, http.StatusOK, procList)
  334. }
  335. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  336. if err := httputils.ParseForm(r); err != nil {
  337. return err
  338. }
  339. name := vars["name"]
  340. newName := r.Form.Get("name")
  341. if err := s.backend.ContainerRename(name, newName); err != nil {
  342. return err
  343. }
  344. w.WriteHeader(http.StatusNoContent)
  345. return nil
  346. }
  347. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  348. if err := httputils.ParseForm(r); err != nil {
  349. return err
  350. }
  351. if err := httputils.CheckForJSON(r); err != nil {
  352. return err
  353. }
  354. var updateConfig container.UpdateConfig
  355. decoder := json.NewDecoder(r.Body)
  356. if err := decoder.Decode(&updateConfig); err != nil {
  357. return err
  358. }
  359. if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") {
  360. updateConfig.PidsLimit = nil
  361. }
  362. if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 {
  363. // Both `0` and `-1` are accepted to set "unlimited" when updating.
  364. // Historically, any negative value was accepted, so treat them as
  365. // "unlimited" as well.
  366. var unlimited int64
  367. updateConfig.PidsLimit = &unlimited
  368. }
  369. hostConfig := &container.HostConfig{
  370. Resources: updateConfig.Resources,
  371. RestartPolicy: updateConfig.RestartPolicy,
  372. }
  373. name := vars["name"]
  374. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  375. if err != nil {
  376. return err
  377. }
  378. return httputils.WriteJSON(w, http.StatusOK, resp)
  379. }
  380. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  381. if err := httputils.ParseForm(r); err != nil {
  382. return err
  383. }
  384. if err := httputils.CheckForJSON(r); err != nil {
  385. return err
  386. }
  387. name := r.Form.Get("name")
  388. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  389. if err != nil {
  390. return err
  391. }
  392. version := httputils.VersionFromContext(ctx)
  393. adjustCPUShares := versions.LessThan(version, "1.19")
  394. // When using API 1.24 and under, the client is responsible for removing the container
  395. if hostConfig != nil && versions.LessThan(version, "1.25") {
  396. hostConfig.AutoRemove = false
  397. }
  398. if hostConfig != nil && versions.LessThan(version, "1.40") {
  399. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  400. for _, m := range hostConfig.Mounts {
  401. if bo := m.BindOptions; bo != nil {
  402. bo.NonRecursive = false
  403. }
  404. }
  405. // Ignore KernelMemoryTCP because it was added in API 1.40.
  406. hostConfig.KernelMemoryTCP = 0
  407. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  408. if hostConfig.IpcMode.IsEmpty() {
  409. hostConfig.IpcMode = container.IPCModeShareable
  410. }
  411. }
  412. if hostConfig != nil && versions.LessThan(version, "1.41") && !s.cgroup2 {
  413. // Older clients expect the default to be "host" on cgroup v1 hosts
  414. if hostConfig.CgroupnsMode.IsEmpty() {
  415. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  416. }
  417. }
  418. var platform *specs.Platform
  419. if versions.GreaterThanOrEqualTo(version, "1.41") {
  420. if v := r.Form.Get("platform"); v != "" {
  421. p, err := platforms.Parse(v)
  422. if err != nil {
  423. return errdefs.InvalidParameter(err)
  424. }
  425. platform = &p
  426. }
  427. }
  428. if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  429. // Don't set a limit if either no limit was specified, or "unlimited" was
  430. // explicitly set.
  431. // Both `0` and `-1` are accepted as "unlimited", and historically any
  432. // negative value was accepted, so treat those as "unlimited" as well.
  433. hostConfig.PidsLimit = nil
  434. }
  435. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  436. Name: name,
  437. Config: config,
  438. HostConfig: hostConfig,
  439. NetworkingConfig: networkingConfig,
  440. AdjustCPUShares: adjustCPUShares,
  441. Platform: platform,
  442. })
  443. if err != nil {
  444. return err
  445. }
  446. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  447. }
  448. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  449. if err := httputils.ParseForm(r); err != nil {
  450. return err
  451. }
  452. name := vars["name"]
  453. config := &types.ContainerRmConfig{
  454. ForceRemove: httputils.BoolValue(r, "force"),
  455. RemoveVolume: httputils.BoolValue(r, "v"),
  456. RemoveLink: httputils.BoolValue(r, "link"),
  457. }
  458. if err := s.backend.ContainerRm(name, config); err != nil {
  459. return err
  460. }
  461. w.WriteHeader(http.StatusNoContent)
  462. return nil
  463. }
  464. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  465. if err := httputils.ParseForm(r); err != nil {
  466. return err
  467. }
  468. height, err := strconv.Atoi(r.Form.Get("h"))
  469. if err != nil {
  470. return errdefs.InvalidParameter(err)
  471. }
  472. width, err := strconv.Atoi(r.Form.Get("w"))
  473. if err != nil {
  474. return errdefs.InvalidParameter(err)
  475. }
  476. return s.backend.ContainerResize(vars["name"], height, width)
  477. }
  478. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  479. err := httputils.ParseForm(r)
  480. if err != nil {
  481. return err
  482. }
  483. containerName := vars["name"]
  484. _, upgrade := r.Header["Upgrade"]
  485. detachKeys := r.FormValue("detachKeys")
  486. hijacker, ok := w.(http.Hijacker)
  487. if !ok {
  488. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  489. }
  490. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  491. conn, _, err := hijacker.Hijack()
  492. if err != nil {
  493. return nil, nil, nil, err
  494. }
  495. // set raw mode
  496. conn.Write([]byte{})
  497. if upgrade {
  498. 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")
  499. } else {
  500. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  501. }
  502. closer := func() error {
  503. httputils.CloseStreams(conn)
  504. return nil
  505. }
  506. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  507. }
  508. attachConfig := &backend.ContainerAttachConfig{
  509. GetStreams: setupStreams,
  510. UseStdin: httputils.BoolValue(r, "stdin"),
  511. UseStdout: httputils.BoolValue(r, "stdout"),
  512. UseStderr: httputils.BoolValue(r, "stderr"),
  513. Logs: httputils.BoolValue(r, "logs"),
  514. Stream: httputils.BoolValue(r, "stream"),
  515. DetachKeys: detachKeys,
  516. MuxStreams: true,
  517. }
  518. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  519. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  520. // Remember to close stream if error happens
  521. conn, _, errHijack := hijacker.Hijack()
  522. if errHijack == nil {
  523. statusCode := errdefs.GetHTTPErrorStatusCode(err)
  524. statusText := http.StatusText(statusCode)
  525. 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())
  526. httputils.CloseStreams(conn)
  527. } else {
  528. logrus.Errorf("Error Hijacking: %v", err)
  529. }
  530. }
  531. return nil
  532. }
  533. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  534. if err := httputils.ParseForm(r); err != nil {
  535. return err
  536. }
  537. containerName := vars["name"]
  538. var err error
  539. detachKeys := r.FormValue("detachKeys")
  540. done := make(chan struct{})
  541. started := make(chan struct{})
  542. version := httputils.VersionFromContext(ctx)
  543. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  544. wsChan := make(chan *websocket.Conn)
  545. h := func(conn *websocket.Conn) {
  546. wsChan <- conn
  547. <-done
  548. }
  549. srv := websocket.Server{Handler: h, Handshake: nil}
  550. go func() {
  551. close(started)
  552. srv.ServeHTTP(w, r)
  553. }()
  554. conn := <-wsChan
  555. // In case version 1.28 and above, a binary frame will be sent.
  556. // See 28176 for details.
  557. if versions.GreaterThanOrEqualTo(version, "1.28") {
  558. conn.PayloadType = websocket.BinaryFrame
  559. }
  560. return conn, conn, conn, nil
  561. }
  562. attachConfig := &backend.ContainerAttachConfig{
  563. GetStreams: setupStreams,
  564. Logs: httputils.BoolValue(r, "logs"),
  565. Stream: httputils.BoolValue(r, "stream"),
  566. DetachKeys: detachKeys,
  567. UseStdin: true,
  568. UseStdout: true,
  569. UseStderr: true,
  570. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  571. }
  572. err = s.backend.ContainerAttach(containerName, attachConfig)
  573. close(done)
  574. select {
  575. case <-started:
  576. if err != nil {
  577. logrus.Errorf("Error attaching websocket: %s", err)
  578. } else {
  579. logrus.Debug("websocket connection was closed by client")
  580. }
  581. return nil
  582. default:
  583. }
  584. return err
  585. }
  586. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  587. if err := httputils.ParseForm(r); err != nil {
  588. return err
  589. }
  590. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  591. if err != nil {
  592. return errdefs.InvalidParameter(err)
  593. }
  594. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  595. if err != nil {
  596. return err
  597. }
  598. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  599. }