container_routes.go 23 KB

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