container_routes.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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. "strings"
  11. "github.com/containerd/containerd/platforms"
  12. "github.com/containerd/log"
  13. "github.com/docker/docker/api/server/httpstatus"
  14. "github.com/docker/docker/api/server/httputils"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/api/types/backend"
  17. "github.com/docker/docker/api/types/container"
  18. "github.com/docker/docker/api/types/filters"
  19. "github.com/docker/docker/api/types/mount"
  20. "github.com/docker/docker/api/types/versions"
  21. containerpkg "github.com/docker/docker/container"
  22. "github.com/docker/docker/errdefs"
  23. "github.com/docker/docker/pkg/ioutils"
  24. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  25. "github.com/pkg/errors"
  26. "golang.org/x/net/websocket"
  27. )
  28. func (s *containerRouter) postCommit(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  29. if err := httputils.ParseForm(r); err != nil {
  30. return err
  31. }
  32. if err := httputils.CheckForJSON(r); err != nil {
  33. return err
  34. }
  35. // TODO: remove pause arg, and always pause in backend
  36. pause := httputils.BoolValue(r, "pause")
  37. version := httputils.VersionFromContext(ctx)
  38. if r.FormValue("pause") == "" && versions.GreaterThanOrEqualTo(version, "1.13") {
  39. pause = true
  40. }
  41. config, _, _, err := s.decoder.DecodeConfig(r.Body)
  42. if err != nil && !errors.Is(err, io.EOF) { // Do not fail if body is empty.
  43. return err
  44. }
  45. ref, err := httputils.RepoTagReference(r.Form.Get("repo"), r.Form.Get("tag"))
  46. if err != nil {
  47. return errdefs.InvalidParameter(err)
  48. }
  49. imgID, err := s.backend.CreateImageFromContainer(ctx, r.Form.Get("container"), &backend.CreateImageConfig{
  50. Pause: pause,
  51. Tag: ref,
  52. Author: r.Form.Get("author"),
  53. Comment: r.Form.Get("comment"),
  54. Config: config,
  55. Changes: r.Form["changes"],
  56. })
  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 := &container.ListOptions{
  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 := &container.LogsOptions{
  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(ctx, 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. if errors.Is(err, io.EOF) {
  410. return errdefs.InvalidParameter(errors.New("invalid JSON: got EOF while reading request body"))
  411. }
  412. return err
  413. }
  414. version := httputils.VersionFromContext(ctx)
  415. adjustCPUShares := versions.LessThan(version, "1.19")
  416. // When using API 1.24 and under, the client is responsible for removing the container
  417. if hostConfig != nil && versions.LessThan(version, "1.25") {
  418. hostConfig.AutoRemove = false
  419. }
  420. if hostConfig != nil && versions.LessThan(version, "1.40") {
  421. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  422. for _, m := range hostConfig.Mounts {
  423. if bo := m.BindOptions; bo != nil {
  424. bo.NonRecursive = false
  425. }
  426. }
  427. // Ignore KernelMemoryTCP because it was added in API 1.40.
  428. hostConfig.KernelMemoryTCP = 0
  429. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  430. if hostConfig.IpcMode.IsEmpty() {
  431. hostConfig.IpcMode = container.IPCModeShareable
  432. }
  433. }
  434. if hostConfig != nil && versions.LessThan(version, "1.41") && !s.cgroup2 {
  435. // Older clients expect the default to be "host" on cgroup v1 hosts
  436. if hostConfig.CgroupnsMode.IsEmpty() {
  437. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  438. }
  439. }
  440. if hostConfig != nil && versions.LessThan(version, "1.42") {
  441. for _, m := range hostConfig.Mounts {
  442. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  443. if bo := m.BindOptions; bo != nil {
  444. bo.CreateMountpoint = false
  445. }
  446. // These combinations are invalid, but weren't validated in API < 1.42.
  447. // We reset them here, so that validation doesn't produce an error.
  448. if o := m.VolumeOptions; o != nil && m.Type != mount.TypeVolume {
  449. m.VolumeOptions = nil
  450. }
  451. if o := m.TmpfsOptions; o != nil && m.Type != mount.TypeTmpfs {
  452. m.TmpfsOptions = nil
  453. }
  454. if bo := m.BindOptions; bo != nil {
  455. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  456. bo.CreateMountpoint = false
  457. }
  458. }
  459. }
  460. if hostConfig != nil && versions.LessThan(version, "1.44") {
  461. if config.Healthcheck != nil {
  462. // StartInterval was added in API 1.44
  463. config.Healthcheck.StartInterval = 0
  464. }
  465. }
  466. if hostConfig != nil && versions.GreaterThanOrEqualTo(version, "1.42") {
  467. // Ignore KernelMemory removed in API 1.42.
  468. hostConfig.KernelMemory = 0
  469. for _, m := range hostConfig.Mounts {
  470. if o := m.VolumeOptions; o != nil && m.Type != mount.TypeVolume {
  471. return errdefs.InvalidParameter(fmt.Errorf("VolumeOptions must not be specified on mount type %q", m.Type))
  472. }
  473. if o := m.BindOptions; o != nil && m.Type != mount.TypeBind {
  474. return errdefs.InvalidParameter(fmt.Errorf("BindOptions must not be specified on mount type %q", m.Type))
  475. }
  476. if o := m.TmpfsOptions; o != nil && m.Type != mount.TypeTmpfs {
  477. return errdefs.InvalidParameter(fmt.Errorf("TmpfsOptions must not be specified on mount type %q", m.Type))
  478. }
  479. }
  480. }
  481. if hostConfig != nil && runtime.GOOS == "linux" && versions.LessThan(version, "1.42") {
  482. // ConsoleSize is not respected by Linux daemon before API 1.42
  483. hostConfig.ConsoleSize = [2]uint{0, 0}
  484. }
  485. if hostConfig != nil && versions.LessThan(version, "1.43") {
  486. // Ignore Annotations because it was added in API v1.43.
  487. hostConfig.Annotations = nil
  488. }
  489. var platform *ocispec.Platform
  490. if versions.GreaterThanOrEqualTo(version, "1.41") {
  491. if v := r.Form.Get("platform"); v != "" {
  492. p, err := platforms.Parse(v)
  493. if err != nil {
  494. return errdefs.InvalidParameter(err)
  495. }
  496. platform = &p
  497. }
  498. }
  499. if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  500. // Don't set a limit if either no limit was specified, or "unlimited" was
  501. // explicitly set.
  502. // Both `0` and `-1` are accepted as "unlimited", and historically any
  503. // negative value was accepted, so treat those as "unlimited" as well.
  504. hostConfig.PidsLimit = nil
  505. }
  506. if hostConfig != nil && versions.LessThan(version, "1.44") {
  507. for _, m := range hostConfig.Mounts {
  508. if m.BindOptions != nil {
  509. // Ignore ReadOnlyNonRecursive because it was added in API 1.44.
  510. m.BindOptions.ReadOnlyNonRecursive = false
  511. if m.BindOptions.ReadOnlyForceRecursive {
  512. return errdefs.InvalidParameter(errors.New("BindOptions.ReadOnlyForceRecursive needs API v1.44 or newer"))
  513. }
  514. }
  515. }
  516. }
  517. if versions.LessThan(version, "1.44") {
  518. // Creating a container connected to several networks is not supported until v1.44.
  519. if networkingConfig != nil && len(networkingConfig.EndpointsConfig) > 1 {
  520. l := make([]string, 0, len(networkingConfig.EndpointsConfig))
  521. for k := range networkingConfig.EndpointsConfig {
  522. l = append(l, k)
  523. }
  524. return errdefs.InvalidParameter(errors.Errorf("Container cannot be created with multiple network endpoints: %s", strings.Join(l, ", ")))
  525. }
  526. }
  527. ccr, err := s.backend.ContainerCreate(ctx, types.ContainerCreateConfig{
  528. Name: name,
  529. Config: config,
  530. HostConfig: hostConfig,
  531. NetworkingConfig: networkingConfig,
  532. AdjustCPUShares: adjustCPUShares,
  533. Platform: platform,
  534. })
  535. if err != nil {
  536. return err
  537. }
  538. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  539. }
  540. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  541. if err := httputils.ParseForm(r); err != nil {
  542. return err
  543. }
  544. name := vars["name"]
  545. config := &types.ContainerRmConfig{
  546. ForceRemove: httputils.BoolValue(r, "force"),
  547. RemoveVolume: httputils.BoolValue(r, "v"),
  548. RemoveLink: httputils.BoolValue(r, "link"),
  549. }
  550. if err := s.backend.ContainerRm(name, config); err != nil {
  551. return err
  552. }
  553. w.WriteHeader(http.StatusNoContent)
  554. return nil
  555. }
  556. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  557. if err := httputils.ParseForm(r); err != nil {
  558. return err
  559. }
  560. height, err := strconv.Atoi(r.Form.Get("h"))
  561. if err != nil {
  562. return errdefs.InvalidParameter(err)
  563. }
  564. width, err := strconv.Atoi(r.Form.Get("w"))
  565. if err != nil {
  566. return errdefs.InvalidParameter(err)
  567. }
  568. return s.backend.ContainerResize(vars["name"], height, width)
  569. }
  570. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  571. err := httputils.ParseForm(r)
  572. if err != nil {
  573. return err
  574. }
  575. containerName := vars["name"]
  576. _, upgrade := r.Header["Upgrade"]
  577. detachKeys := r.FormValue("detachKeys")
  578. hijacker, ok := w.(http.Hijacker)
  579. if !ok {
  580. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  581. }
  582. contentType := types.MediaTypeRawStream
  583. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  584. conn, _, err := hijacker.Hijack()
  585. if err != nil {
  586. return nil, nil, nil, err
  587. }
  588. // set raw mode
  589. conn.Write([]byte{})
  590. if upgrade {
  591. if multiplexed && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  592. contentType = types.MediaTypeMultiplexedStream
  593. }
  594. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: "+contentType+"\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  595. } else {
  596. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  597. }
  598. closer := func() error {
  599. httputils.CloseStreams(conn)
  600. return nil
  601. }
  602. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  603. }
  604. attachConfig := &backend.ContainerAttachConfig{
  605. GetStreams: setupStreams,
  606. UseStdin: httputils.BoolValue(r, "stdin"),
  607. UseStdout: httputils.BoolValue(r, "stdout"),
  608. UseStderr: httputils.BoolValue(r, "stderr"),
  609. Logs: httputils.BoolValue(r, "logs"),
  610. Stream: httputils.BoolValue(r, "stream"),
  611. DetachKeys: detachKeys,
  612. MuxStreams: true,
  613. }
  614. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  615. log.G(ctx).WithError(err).Errorf("Handler for %s %s returned error", r.Method, r.URL.Path)
  616. // Remember to close stream if error happens
  617. conn, _, errHijack := hijacker.Hijack()
  618. if errHijack != nil {
  619. log.G(ctx).WithError(err).Errorf("Handler for %s %s: unable to close stream; error when hijacking connection", r.Method, r.URL.Path)
  620. } else {
  621. statusCode := httpstatus.FromError(err)
  622. statusText := http.StatusText(statusCode)
  623. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: %s\r\n\r\n%s\r\n", statusCode, statusText, contentType, err.Error())
  624. httputils.CloseStreams(conn)
  625. }
  626. }
  627. return nil
  628. }
  629. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  630. if err := httputils.ParseForm(r); err != nil {
  631. return err
  632. }
  633. containerName := vars["name"]
  634. var err error
  635. detachKeys := r.FormValue("detachKeys")
  636. done := make(chan struct{})
  637. started := make(chan struct{})
  638. version := httputils.VersionFromContext(ctx)
  639. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  640. wsChan := make(chan *websocket.Conn)
  641. h := func(conn *websocket.Conn) {
  642. wsChan <- conn
  643. <-done
  644. }
  645. srv := websocket.Server{Handler: h, Handshake: nil}
  646. go func() {
  647. close(started)
  648. srv.ServeHTTP(w, r)
  649. }()
  650. conn := <-wsChan
  651. // In case version 1.28 and above, a binary frame will be sent.
  652. // See 28176 for details.
  653. if versions.GreaterThanOrEqualTo(version, "1.28") {
  654. conn.PayloadType = websocket.BinaryFrame
  655. }
  656. return conn, conn, conn, nil
  657. }
  658. useStdin, useStdout, useStderr := true, true, true
  659. if versions.GreaterThanOrEqualTo(version, "1.42") {
  660. useStdin = httputils.BoolValue(r, "stdin")
  661. useStdout = httputils.BoolValue(r, "stdout")
  662. useStderr = httputils.BoolValue(r, "stderr")
  663. }
  664. attachConfig := &backend.ContainerAttachConfig{
  665. GetStreams: setupStreams,
  666. UseStdin: useStdin,
  667. UseStdout: useStdout,
  668. UseStderr: useStderr,
  669. Logs: httputils.BoolValue(r, "logs"),
  670. Stream: httputils.BoolValue(r, "stream"),
  671. DetachKeys: detachKeys,
  672. MuxStreams: false, // never multiplex, as we rely on websocket to manage distinct streams
  673. }
  674. err = s.backend.ContainerAttach(containerName, attachConfig)
  675. close(done)
  676. select {
  677. case <-started:
  678. if err != nil {
  679. log.G(ctx).Errorf("Error attaching websocket: %s", err)
  680. } else {
  681. log.G(ctx).Debug("websocket connection was closed by client")
  682. }
  683. return nil
  684. default:
  685. }
  686. return err
  687. }
  688. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  689. if err := httputils.ParseForm(r); err != nil {
  690. return err
  691. }
  692. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  693. if err != nil {
  694. return err
  695. }
  696. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  697. if err != nil {
  698. return err
  699. }
  700. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  701. }