container_routes.go 21 KB

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