container_routes.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. "runtime"
  9. "strconv"
  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. 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. contentType := types.MediaTypeRawStream
  135. if !tty && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  136. contentType = types.MediaTypeMultiplexedStream
  137. }
  138. w.Header().Set("Content-Type", contentType)
  139. // if has a tty, we're not muxing streams. if it doesn't, we are. simple.
  140. // this is the point of no return for writing a response. once we call
  141. // WriteLogStream, the response has been started and errors will be
  142. // returned in band by WriteLogStream
  143. httputils.WriteLogStream(ctx, w, msgs, logsConfig, !tty)
  144. return nil
  145. }
  146. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  147. return s.backend.ContainerExport(vars["name"], w)
  148. }
  149. type bodyOnStartError struct{}
  150. func (bodyOnStartError) Error() string {
  151. return "starting container with non-empty request body was deprecated since API v1.22 and removed in v1.24"
  152. }
  153. func (bodyOnStartError) InvalidParameter() {}
  154. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  155. // If contentLength is -1, we can assumed chunked encoding
  156. // or more technically that the length is unknown
  157. // https://golang.org/src/pkg/net/http/request.go#L139
  158. // net/http otherwise seems to swallow any headers related to chunked encoding
  159. // including r.TransferEncoding
  160. // allow a nil body for backwards compatibility
  161. version := httputils.VersionFromContext(ctx)
  162. var hostConfig *container.HostConfig
  163. // A non-nil json object is at least 7 characters.
  164. if r.ContentLength > 7 || r.ContentLength == -1 {
  165. if versions.GreaterThanOrEqualTo(version, "1.24") {
  166. return bodyOnStartError{}
  167. }
  168. if err := httputils.CheckForJSON(r); err != nil {
  169. return err
  170. }
  171. c, err := s.decoder.DecodeHostConfig(r.Body)
  172. if err != nil {
  173. return err
  174. }
  175. hostConfig = c
  176. }
  177. if err := httputils.ParseForm(r); err != nil {
  178. return err
  179. }
  180. checkpoint := r.Form.Get("checkpoint")
  181. checkpointDir := r.Form.Get("checkpoint-dir")
  182. if err := s.backend.ContainerStart(vars["name"], hostConfig, checkpoint, checkpointDir); err != nil {
  183. return err
  184. }
  185. w.WriteHeader(http.StatusNoContent)
  186. return nil
  187. }
  188. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  189. if err := httputils.ParseForm(r); err != nil {
  190. return err
  191. }
  192. var (
  193. options container.StopOptions
  194. version = httputils.VersionFromContext(ctx)
  195. )
  196. if versions.GreaterThanOrEqualTo(version, "1.42") {
  197. options.Signal = r.Form.Get("signal")
  198. }
  199. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  200. valSeconds, err := strconv.Atoi(tmpSeconds)
  201. if err != nil {
  202. return err
  203. }
  204. options.Timeout = &valSeconds
  205. }
  206. if err := s.backend.ContainerStop(ctx, vars["name"], options); err != nil {
  207. return err
  208. }
  209. w.WriteHeader(http.StatusNoContent)
  210. return nil
  211. }
  212. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  213. if err := httputils.ParseForm(r); err != nil {
  214. return err
  215. }
  216. name := vars["name"]
  217. if err := s.backend.ContainerKill(name, r.Form.Get("signal")); err != nil {
  218. var isStopped bool
  219. if errdefs.IsConflict(err) {
  220. isStopped = true
  221. }
  222. // Return error that's not caused because the container is stopped.
  223. // Return error if the container is not running and the api is >= 1.20
  224. // to keep backwards compatibility.
  225. version := httputils.VersionFromContext(ctx)
  226. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  227. return errors.Wrapf(err, "Cannot kill container: %s", name)
  228. }
  229. }
  230. w.WriteHeader(http.StatusNoContent)
  231. return nil
  232. }
  233. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  234. if err := httputils.ParseForm(r); err != nil {
  235. return err
  236. }
  237. var (
  238. options container.StopOptions
  239. version = httputils.VersionFromContext(ctx)
  240. )
  241. if versions.GreaterThanOrEqualTo(version, "1.42") {
  242. options.Signal = r.Form.Get("signal")
  243. }
  244. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  245. valSeconds, err := strconv.Atoi(tmpSeconds)
  246. if err != nil {
  247. return err
  248. }
  249. options.Timeout = &valSeconds
  250. }
  251. if err := s.backend.ContainerRestart(ctx, vars["name"], options); err != nil {
  252. return err
  253. }
  254. w.WriteHeader(http.StatusNoContent)
  255. return nil
  256. }
  257. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  258. if err := httputils.ParseForm(r); err != nil {
  259. return err
  260. }
  261. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  262. return err
  263. }
  264. w.WriteHeader(http.StatusNoContent)
  265. return nil
  266. }
  267. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  268. if err := httputils.ParseForm(r); err != nil {
  269. return err
  270. }
  271. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  272. return err
  273. }
  274. w.WriteHeader(http.StatusNoContent)
  275. return nil
  276. }
  277. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  278. // Behavior changed in version 1.30 to handle wait condition and to
  279. // return headers immediately.
  280. version := httputils.VersionFromContext(ctx)
  281. legacyBehaviorPre130 := versions.LessThan(version, "1.30")
  282. legacyRemovalWaitPre134 := false
  283. // The wait condition defaults to "not-running".
  284. waitCondition := containerpkg.WaitConditionNotRunning
  285. if !legacyBehaviorPre130 {
  286. if err := httputils.ParseForm(r); err != nil {
  287. return err
  288. }
  289. if v := r.Form.Get("condition"); v != "" {
  290. switch container.WaitCondition(v) {
  291. case container.WaitConditionNextExit:
  292. waitCondition = containerpkg.WaitConditionNextExit
  293. case container.WaitConditionRemoved:
  294. waitCondition = containerpkg.WaitConditionRemoved
  295. legacyRemovalWaitPre134 = versions.LessThan(version, "1.34")
  296. default:
  297. return errdefs.InvalidParameter(errors.Errorf("invalid condition: %q", v))
  298. }
  299. }
  300. }
  301. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  302. if err != nil {
  303. return err
  304. }
  305. w.Header().Set("Content-Type", "application/json")
  306. if !legacyBehaviorPre130 {
  307. // Write response header immediately.
  308. w.WriteHeader(http.StatusOK)
  309. if flusher, ok := w.(http.Flusher); ok {
  310. flusher.Flush()
  311. }
  312. }
  313. // Block on the result of the wait operation.
  314. status := <-waitC
  315. // With API < 1.34, wait on WaitConditionRemoved did not return
  316. // in case container removal failed. The only way to report an
  317. // error back to the client is to not write anything (i.e. send
  318. // an empty response which will be treated as an error).
  319. if legacyRemovalWaitPre134 && status.Err() != nil {
  320. return nil
  321. }
  322. var waitError *container.WaitExitError
  323. if status.Err() != nil {
  324. waitError = &container.WaitExitError{Message: status.Err().Error()}
  325. }
  326. return json.NewEncoder(w).Encode(&container.WaitResponse{
  327. StatusCode: int64(status.ExitCode()),
  328. Error: waitError,
  329. })
  330. }
  331. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  332. changes, err := s.backend.ContainerChanges(vars["name"])
  333. if err != nil {
  334. return err
  335. }
  336. return httputils.WriteJSON(w, http.StatusOK, changes)
  337. }
  338. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  339. if err := httputils.ParseForm(r); err != nil {
  340. return err
  341. }
  342. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  343. if err != nil {
  344. return err
  345. }
  346. return httputils.WriteJSON(w, http.StatusOK, procList)
  347. }
  348. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  349. if err := httputils.ParseForm(r); err != nil {
  350. return err
  351. }
  352. name := vars["name"]
  353. newName := r.Form.Get("name")
  354. if err := s.backend.ContainerRename(name, newName); err != nil {
  355. return err
  356. }
  357. w.WriteHeader(http.StatusNoContent)
  358. return nil
  359. }
  360. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  361. if err := httputils.ParseForm(r); err != nil {
  362. return err
  363. }
  364. var updateConfig container.UpdateConfig
  365. if err := httputils.ReadJSON(r, &updateConfig); err != nil {
  366. return err
  367. }
  368. if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") {
  369. updateConfig.PidsLimit = nil
  370. }
  371. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  372. // Ignore KernelMemory removed in API 1.42.
  373. updateConfig.KernelMemory = 0
  374. }
  375. if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 {
  376. // Both `0` and `-1` are accepted to set "unlimited" when updating.
  377. // Historically, any negative value was accepted, so treat them as
  378. // "unlimited" as well.
  379. var unlimited int64
  380. updateConfig.PidsLimit = &unlimited
  381. }
  382. hostConfig := &container.HostConfig{
  383. Resources: updateConfig.Resources,
  384. RestartPolicy: updateConfig.RestartPolicy,
  385. }
  386. name := vars["name"]
  387. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  388. if err != nil {
  389. return err
  390. }
  391. return httputils.WriteJSON(w, http.StatusOK, resp)
  392. }
  393. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  394. if err := httputils.ParseForm(r); err != nil {
  395. return err
  396. }
  397. if err := httputils.CheckForJSON(r); err != nil {
  398. return err
  399. }
  400. name := r.Form.Get("name")
  401. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  402. if err != nil {
  403. return err
  404. }
  405. version := httputils.VersionFromContext(ctx)
  406. adjustCPUShares := versions.LessThan(version, "1.19")
  407. // When using API 1.24 and under, the client is responsible for removing the container
  408. if hostConfig != nil && versions.LessThan(version, "1.25") {
  409. hostConfig.AutoRemove = false
  410. }
  411. if hostConfig != nil && versions.LessThan(version, "1.40") {
  412. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  413. for _, m := range hostConfig.Mounts {
  414. if bo := m.BindOptions; bo != nil {
  415. bo.NonRecursive = false
  416. }
  417. }
  418. // Ignore KernelMemoryTCP because it was added in API 1.40.
  419. hostConfig.KernelMemoryTCP = 0
  420. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  421. if hostConfig.IpcMode.IsEmpty() {
  422. hostConfig.IpcMode = container.IPCModeShareable
  423. }
  424. }
  425. if hostConfig != nil && versions.LessThan(version, "1.41") && !s.cgroup2 {
  426. // Older clients expect the default to be "host" on cgroup v1 hosts
  427. if hostConfig.CgroupnsMode.IsEmpty() {
  428. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  429. }
  430. }
  431. if hostConfig != nil && versions.GreaterThanOrEqualTo(version, "1.42") {
  432. // Ignore KernelMemory removed in API 1.42.
  433. hostConfig.KernelMemory = 0
  434. }
  435. if hostConfig != nil && runtime.GOOS == "linux" && versions.LessThan(version, "1.42") {
  436. // ConsoleSize is not respected by Linux daemon before API 1.42
  437. hostConfig.ConsoleSize = [2]uint{0, 0}
  438. }
  439. var platform *specs.Platform
  440. if versions.GreaterThanOrEqualTo(version, "1.41") {
  441. if v := r.Form.Get("platform"); v != "" {
  442. p, err := platforms.Parse(v)
  443. if err != nil {
  444. return errdefs.InvalidParameter(err)
  445. }
  446. platform = &p
  447. }
  448. }
  449. if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  450. // Don't set a limit if either no limit was specified, or "unlimited" was
  451. // explicitly set.
  452. // Both `0` and `-1` are accepted as "unlimited", and historically any
  453. // negative value was accepted, so treat those as "unlimited" as well.
  454. hostConfig.PidsLimit = nil
  455. }
  456. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  457. Name: name,
  458. Config: config,
  459. HostConfig: hostConfig,
  460. NetworkingConfig: networkingConfig,
  461. AdjustCPUShares: adjustCPUShares,
  462. Platform: platform,
  463. })
  464. if err != nil {
  465. return err
  466. }
  467. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  468. }
  469. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  470. if err := httputils.ParseForm(r); err != nil {
  471. return err
  472. }
  473. name := vars["name"]
  474. config := &types.ContainerRmConfig{
  475. ForceRemove: httputils.BoolValue(r, "force"),
  476. RemoveVolume: httputils.BoolValue(r, "v"),
  477. RemoveLink: httputils.BoolValue(r, "link"),
  478. }
  479. if err := s.backend.ContainerRm(name, config); err != nil {
  480. return err
  481. }
  482. w.WriteHeader(http.StatusNoContent)
  483. return nil
  484. }
  485. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  486. if err := httputils.ParseForm(r); err != nil {
  487. return err
  488. }
  489. height, err := strconv.Atoi(r.Form.Get("h"))
  490. if err != nil {
  491. return errdefs.InvalidParameter(err)
  492. }
  493. width, err := strconv.Atoi(r.Form.Get("w"))
  494. if err != nil {
  495. return errdefs.InvalidParameter(err)
  496. }
  497. return s.backend.ContainerResize(vars["name"], height, width)
  498. }
  499. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  500. err := httputils.ParseForm(r)
  501. if err != nil {
  502. return err
  503. }
  504. containerName := vars["name"]
  505. _, upgrade := r.Header["Upgrade"]
  506. detachKeys := r.FormValue("detachKeys")
  507. hijacker, ok := w.(http.Hijacker)
  508. if !ok {
  509. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  510. }
  511. contentType := types.MediaTypeRawStream
  512. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  513. conn, _, err := hijacker.Hijack()
  514. if err != nil {
  515. return nil, nil, nil, err
  516. }
  517. // set raw mode
  518. conn.Write([]byte{})
  519. if upgrade {
  520. if multiplexed && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  521. contentType = types.MediaTypeMultiplexedStream
  522. }
  523. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: "+contentType+"\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  524. } else {
  525. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  526. }
  527. closer := func() error {
  528. httputils.CloseStreams(conn)
  529. return nil
  530. }
  531. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  532. }
  533. attachConfig := &backend.ContainerAttachConfig{
  534. GetStreams: setupStreams,
  535. UseStdin: httputils.BoolValue(r, "stdin"),
  536. UseStdout: httputils.BoolValue(r, "stdout"),
  537. UseStderr: httputils.BoolValue(r, "stderr"),
  538. Logs: httputils.BoolValue(r, "logs"),
  539. Stream: httputils.BoolValue(r, "stream"),
  540. DetachKeys: detachKeys,
  541. MuxStreams: true,
  542. }
  543. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  544. logrus.WithError(err).Errorf("Handler for %s %s returned error", r.Method, r.URL.Path)
  545. // Remember to close stream if error happens
  546. conn, _, errHijack := hijacker.Hijack()
  547. if errHijack != nil {
  548. logrus.WithError(err).Errorf("Handler for %s %s: unable to close stream; error when hijacking connection", r.Method, r.URL.Path)
  549. } else {
  550. statusCode := httpstatus.FromError(err)
  551. statusText := http.StatusText(statusCode)
  552. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: %s\r\n\r\n%s\r\n", statusCode, statusText, contentType, err.Error())
  553. httputils.CloseStreams(conn)
  554. }
  555. }
  556. return nil
  557. }
  558. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  559. if err := httputils.ParseForm(r); err != nil {
  560. return err
  561. }
  562. containerName := vars["name"]
  563. var err error
  564. detachKeys := r.FormValue("detachKeys")
  565. done := make(chan struct{})
  566. started := make(chan struct{})
  567. version := httputils.VersionFromContext(ctx)
  568. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  569. wsChan := make(chan *websocket.Conn)
  570. h := func(conn *websocket.Conn) {
  571. wsChan <- conn
  572. <-done
  573. }
  574. srv := websocket.Server{Handler: h, Handshake: nil}
  575. go func() {
  576. close(started)
  577. srv.ServeHTTP(w, r)
  578. }()
  579. conn := <-wsChan
  580. // In case version 1.28 and above, a binary frame will be sent.
  581. // See 28176 for details.
  582. if versions.GreaterThanOrEqualTo(version, "1.28") {
  583. conn.PayloadType = websocket.BinaryFrame
  584. }
  585. return conn, conn, conn, nil
  586. }
  587. useStdin, useStdout, useStderr := true, true, true
  588. if versions.GreaterThanOrEqualTo(version, "1.42") {
  589. useStdin = httputils.BoolValue(r, "stdin")
  590. useStdout = httputils.BoolValue(r, "stdout")
  591. useStderr = httputils.BoolValue(r, "stderr")
  592. }
  593. attachConfig := &backend.ContainerAttachConfig{
  594. GetStreams: setupStreams,
  595. UseStdin: useStdin,
  596. UseStdout: useStdout,
  597. UseStderr: useStderr,
  598. Logs: httputils.BoolValue(r, "logs"),
  599. Stream: httputils.BoolValue(r, "stream"),
  600. DetachKeys: detachKeys,
  601. MuxStreams: false, // never multiplex, as we rely on websocket to manage distinct streams
  602. }
  603. err = s.backend.ContainerAttach(containerName, attachConfig)
  604. close(done)
  605. select {
  606. case <-started:
  607. if err != nil {
  608. logrus.Errorf("Error attaching websocket: %s", err)
  609. } else {
  610. logrus.Debug("websocket connection was closed by client")
  611. }
  612. return nil
  613. default:
  614. }
  615. return err
  616. }
  617. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  618. if err := httputils.ParseForm(r); err != nil {
  619. return err
  620. }
  621. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  622. if err != nil {
  623. return err
  624. }
  625. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  626. if err != nil {
  627. return err
  628. }
  629. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  630. }