container_routes.go 24 KB

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