container_routes.go 24 KB

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