container_routes.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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/network"
  21. "github.com/docker/docker/api/types/versions"
  22. containerpkg "github.com/docker/docker/container"
  23. "github.com/docker/docker/errdefs"
  24. "github.com/docker/docker/pkg/ioutils"
  25. "github.com/docker/docker/runconfig"
  26. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  27. "github.com/pkg/errors"
  28. "golang.org/x/net/websocket"
  29. )
  30. func (s *containerRouter) postCommit(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  31. if err := httputils.ParseForm(r); err != nil {
  32. return err
  33. }
  34. if err := httputils.CheckForJSON(r); err != nil {
  35. return err
  36. }
  37. config, _, _, err := s.decoder.DecodeConfig(r.Body)
  38. if err != nil && !errors.Is(err, io.EOF) { // Do not fail if body is empty.
  39. return err
  40. }
  41. ref, err := httputils.RepoTagReference(r.Form.Get("repo"), r.Form.Get("tag"))
  42. if err != nil {
  43. return errdefs.InvalidParameter(err)
  44. }
  45. imgID, err := s.backend.CreateImageFromContainer(ctx, r.Form.Get("container"), &backend.CreateImageConfig{
  46. Pause: httputils.BoolValueOrDefault(r, "pause", true), // TODO(dnephin): remove pause arg, and always pause in backend
  47. Tag: ref,
  48. Author: r.Form.Get("author"),
  49. Comment: r.Form.Get("comment"),
  50. Config: config,
  51. Changes: r.Form["changes"],
  52. })
  53. if err != nil {
  54. return err
  55. }
  56. return httputils.WriteJSON(w, http.StatusCreated, &types.IDResponse{ID: imgID})
  57. }
  58. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  59. if err := httputils.ParseForm(r); err != nil {
  60. return err
  61. }
  62. filter, err := filters.FromJSON(r.Form.Get("filters"))
  63. if err != nil {
  64. return err
  65. }
  66. config := &container.ListOptions{
  67. All: httputils.BoolValue(r, "all"),
  68. Size: httputils.BoolValue(r, "size"),
  69. Since: r.Form.Get("since"),
  70. Before: r.Form.Get("before"),
  71. Filters: filter,
  72. }
  73. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  74. limit, err := strconv.Atoi(tmpLimit)
  75. if err != nil {
  76. return err
  77. }
  78. config.Limit = limit
  79. }
  80. containers, err := s.backend.Containers(ctx, config)
  81. if err != nil {
  82. return err
  83. }
  84. return httputils.WriteJSON(w, http.StatusOK, containers)
  85. }
  86. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  87. if err := httputils.ParseForm(r); err != nil {
  88. return err
  89. }
  90. stream := httputils.BoolValueOrDefault(r, "stream", true)
  91. if !stream {
  92. w.Header().Set("Content-Type", "application/json")
  93. }
  94. var oneShot bool
  95. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.41") {
  96. oneShot = httputils.BoolValueOrDefault(r, "one-shot", false)
  97. }
  98. return s.backend.ContainerStats(ctx, vars["name"], &backend.ContainerStatsConfig{
  99. Stream: stream,
  100. OneShot: oneShot,
  101. OutStream: w,
  102. })
  103. }
  104. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  105. if err := httputils.ParseForm(r); err != nil {
  106. return err
  107. }
  108. // Args are validated before the stream starts because when it starts we're
  109. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  110. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  111. // any error after the stream starts (i.e. container not found, wrong parameters)
  112. // with the appropriate status code.
  113. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  114. if !(stdout || stderr) {
  115. return errdefs.InvalidParameter(errors.New("Bad parameters: you must choose at least one stream"))
  116. }
  117. containerName := vars["name"]
  118. logsConfig := &container.LogsOptions{
  119. Follow: httputils.BoolValue(r, "follow"),
  120. Timestamps: httputils.BoolValue(r, "timestamps"),
  121. Since: r.Form.Get("since"),
  122. Until: r.Form.Get("until"),
  123. Tail: r.Form.Get("tail"),
  124. ShowStdout: stdout,
  125. ShowStderr: stderr,
  126. Details: httputils.BoolValue(r, "details"),
  127. }
  128. msgs, tty, err := s.backend.ContainerLogs(ctx, containerName, logsConfig)
  129. if err != nil {
  130. return err
  131. }
  132. contentType := types.MediaTypeRawStream
  133. if !tty && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  134. contentType = types.MediaTypeMultiplexedStream
  135. }
  136. w.Header().Set("Content-Type", contentType)
  137. // if has a tty, we're not muxing streams. if it doesn't, we are. simple.
  138. // this is the point of no return for writing a response. once we call
  139. // WriteLogStream, the response has been started and errors will be
  140. // returned in band by WriteLogStream
  141. httputils.WriteLogStream(ctx, w, msgs, logsConfig, !tty)
  142. return nil
  143. }
  144. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  145. return s.backend.ContainerExport(ctx, vars["name"], w)
  146. }
  147. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  148. // If contentLength is -1, we can assumed chunked encoding
  149. // or more technically that the length is unknown
  150. // https://golang.org/src/pkg/net/http/request.go#L139
  151. // net/http otherwise seems to swallow any headers related to chunked encoding
  152. // including r.TransferEncoding
  153. // allow a nil body for backwards compatibility
  154. //
  155. // A non-nil json object is at least 7 characters.
  156. if r.ContentLength > 7 || r.ContentLength == -1 {
  157. return errdefs.InvalidParameter(errors.New("starting container with non-empty request body was deprecated since API v1.22 and removed in v1.24"))
  158. }
  159. if err := httputils.ParseForm(r); err != nil {
  160. return err
  161. }
  162. if err := s.backend.ContainerStart(ctx, vars["name"], r.Form.Get("checkpoint"), r.Form.Get("checkpoint-dir")); err != nil {
  163. return err
  164. }
  165. w.WriteHeader(http.StatusNoContent)
  166. return nil
  167. }
  168. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  169. if err := httputils.ParseForm(r); err != nil {
  170. return err
  171. }
  172. var (
  173. options container.StopOptions
  174. version = httputils.VersionFromContext(ctx)
  175. )
  176. if versions.GreaterThanOrEqualTo(version, "1.42") {
  177. options.Signal = r.Form.Get("signal")
  178. }
  179. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  180. valSeconds, err := strconv.Atoi(tmpSeconds)
  181. if err != nil {
  182. return err
  183. }
  184. options.Timeout = &valSeconds
  185. }
  186. if err := s.backend.ContainerStop(ctx, vars["name"], options); err != nil {
  187. return err
  188. }
  189. w.WriteHeader(http.StatusNoContent)
  190. return nil
  191. }
  192. func (s *containerRouter) postContainersKill(_ 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. name := vars["name"]
  197. if err := s.backend.ContainerKill(name, r.Form.Get("signal")); err != nil {
  198. return errors.Wrapf(err, "cannot kill container: %s", name)
  199. }
  200. w.WriteHeader(http.StatusNoContent)
  201. return nil
  202. }
  203. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  204. if err := httputils.ParseForm(r); err != nil {
  205. return err
  206. }
  207. var (
  208. options container.StopOptions
  209. version = httputils.VersionFromContext(ctx)
  210. )
  211. if versions.GreaterThanOrEqualTo(version, "1.42") {
  212. options.Signal = r.Form.Get("signal")
  213. }
  214. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  215. valSeconds, err := strconv.Atoi(tmpSeconds)
  216. if err != nil {
  217. return err
  218. }
  219. options.Timeout = &valSeconds
  220. }
  221. if err := s.backend.ContainerRestart(ctx, vars["name"], options); err != nil {
  222. return err
  223. }
  224. w.WriteHeader(http.StatusNoContent)
  225. return nil
  226. }
  227. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  228. if err := httputils.ParseForm(r); err != nil {
  229. return err
  230. }
  231. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  232. return err
  233. }
  234. w.WriteHeader(http.StatusNoContent)
  235. return nil
  236. }
  237. func (s *containerRouter) postContainersUnpause(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. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  242. return err
  243. }
  244. w.WriteHeader(http.StatusNoContent)
  245. return nil
  246. }
  247. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  248. // Behavior changed in version 1.30 to handle wait condition and to
  249. // return headers immediately.
  250. version := httputils.VersionFromContext(ctx)
  251. legacyBehaviorPre130 := versions.LessThan(version, "1.30")
  252. legacyRemovalWaitPre134 := false
  253. // The wait condition defaults to "not-running".
  254. waitCondition := containerpkg.WaitConditionNotRunning
  255. if !legacyBehaviorPre130 {
  256. if err := httputils.ParseForm(r); err != nil {
  257. return err
  258. }
  259. if v := r.Form.Get("condition"); v != "" {
  260. switch container.WaitCondition(v) {
  261. case container.WaitConditionNotRunning:
  262. waitCondition = containerpkg.WaitConditionNotRunning
  263. case container.WaitConditionNextExit:
  264. waitCondition = containerpkg.WaitConditionNextExit
  265. case container.WaitConditionRemoved:
  266. waitCondition = containerpkg.WaitConditionRemoved
  267. legacyRemovalWaitPre134 = versions.LessThan(version, "1.34")
  268. default:
  269. return errdefs.InvalidParameter(errors.Errorf("invalid condition: %q", v))
  270. }
  271. }
  272. }
  273. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  274. if err != nil {
  275. return err
  276. }
  277. w.Header().Set("Content-Type", "application/json")
  278. if !legacyBehaviorPre130 {
  279. // Write response header immediately.
  280. w.WriteHeader(http.StatusOK)
  281. if flusher, ok := w.(http.Flusher); ok {
  282. flusher.Flush()
  283. }
  284. }
  285. // Block on the result of the wait operation.
  286. status := <-waitC
  287. // With API < 1.34, wait on WaitConditionRemoved did not return
  288. // in case container removal failed. The only way to report an
  289. // error back to the client is to not write anything (i.e. send
  290. // an empty response which will be treated as an error).
  291. if legacyRemovalWaitPre134 && status.Err() != nil {
  292. return nil
  293. }
  294. var waitError *container.WaitExitError
  295. if status.Err() != nil {
  296. waitError = &container.WaitExitError{Message: status.Err().Error()}
  297. }
  298. return json.NewEncoder(w).Encode(&container.WaitResponse{
  299. StatusCode: int64(status.ExitCode()),
  300. Error: waitError,
  301. })
  302. }
  303. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  304. changes, err := s.backend.ContainerChanges(ctx, vars["name"])
  305. if err != nil {
  306. return err
  307. }
  308. return httputils.WriteJSON(w, http.StatusOK, changes)
  309. }
  310. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  311. if err := httputils.ParseForm(r); err != nil {
  312. return err
  313. }
  314. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  315. if err != nil {
  316. return err
  317. }
  318. return httputils.WriteJSON(w, http.StatusOK, procList)
  319. }
  320. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  321. if err := httputils.ParseForm(r); err != nil {
  322. return err
  323. }
  324. name := vars["name"]
  325. newName := r.Form.Get("name")
  326. if err := s.backend.ContainerRename(name, newName); err != nil {
  327. return err
  328. }
  329. w.WriteHeader(http.StatusNoContent)
  330. return nil
  331. }
  332. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  333. if err := httputils.ParseForm(r); err != nil {
  334. return err
  335. }
  336. var updateConfig container.UpdateConfig
  337. if err := httputils.ReadJSON(r, &updateConfig); err != nil {
  338. return err
  339. }
  340. if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") {
  341. updateConfig.PidsLimit = nil
  342. }
  343. if versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  344. // Ignore KernelMemory removed in API 1.42.
  345. updateConfig.KernelMemory = 0
  346. }
  347. if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 {
  348. // Both `0` and `-1` are accepted to set "unlimited" when updating.
  349. // Historically, any negative value was accepted, so treat them as
  350. // "unlimited" as well.
  351. var unlimited int64
  352. updateConfig.PidsLimit = &unlimited
  353. }
  354. hostConfig := &container.HostConfig{
  355. Resources: updateConfig.Resources,
  356. RestartPolicy: updateConfig.RestartPolicy,
  357. }
  358. name := vars["name"]
  359. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  360. if err != nil {
  361. return err
  362. }
  363. return httputils.WriteJSON(w, http.StatusOK, resp)
  364. }
  365. func (s *containerRouter) postContainersCreate(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. if err := httputils.CheckForJSON(r); err != nil {
  370. return err
  371. }
  372. name := r.Form.Get("name")
  373. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  374. if err != nil {
  375. if errors.Is(err, io.EOF) {
  376. return errdefs.InvalidParameter(errors.New("invalid JSON: got EOF while reading request body"))
  377. }
  378. return err
  379. }
  380. if config == nil {
  381. return errdefs.InvalidParameter(runconfig.ErrEmptyConfig)
  382. }
  383. if hostConfig == nil {
  384. hostConfig = &container.HostConfig{}
  385. }
  386. if networkingConfig == nil {
  387. networkingConfig = &network.NetworkingConfig{}
  388. }
  389. if networkingConfig.EndpointsConfig == nil {
  390. networkingConfig.EndpointsConfig = make(map[string]*network.EndpointSettings)
  391. }
  392. // The NetworkMode "default" is used as a way to express a container should
  393. // be attached to the OS-dependant default network, in an OS-independent
  394. // way. Doing this conversion as soon as possible ensures we have less
  395. // NetworkMode to handle down the path (including in the
  396. // backward-compatibility layer we have just below).
  397. //
  398. // Note that this is not the only place where this conversion has to be
  399. // done (as there are various other places where containers get created).
  400. if hostConfig.NetworkMode == "" || hostConfig.NetworkMode.IsDefault() {
  401. hostConfig.NetworkMode = runconfig.DefaultDaemonNetworkMode()
  402. if nw, ok := networkingConfig.EndpointsConfig[network.NetworkDefault]; ok {
  403. networkingConfig.EndpointsConfig[hostConfig.NetworkMode.NetworkName()] = nw
  404. delete(networkingConfig.EndpointsConfig, network.NetworkDefault)
  405. }
  406. }
  407. version := httputils.VersionFromContext(ctx)
  408. // When using API 1.24 and under, the client is responsible for removing the container
  409. if versions.LessThan(version, "1.25") {
  410. hostConfig.AutoRemove = false
  411. }
  412. if versions.LessThan(version, "1.40") {
  413. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  414. for _, m := range hostConfig.Mounts {
  415. if bo := m.BindOptions; bo != nil {
  416. bo.NonRecursive = false
  417. }
  418. }
  419. // Ignore KernelMemoryTCP because it was added in API 1.40.
  420. hostConfig.KernelMemoryTCP = 0
  421. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  422. if hostConfig.IpcMode.IsEmpty() {
  423. hostConfig.IpcMode = container.IPCModeShareable
  424. }
  425. }
  426. if versions.LessThan(version, "1.41") {
  427. // Older clients expect the default to be "host" on cgroup v1 hosts
  428. if !s.cgroup2 && hostConfig.CgroupnsMode.IsEmpty() {
  429. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  430. }
  431. }
  432. var platform *ocispec.Platform
  433. if versions.GreaterThanOrEqualTo(version, "1.41") {
  434. if v := r.Form.Get("platform"); v != "" {
  435. p, err := platforms.Parse(v)
  436. if err != nil {
  437. return errdefs.InvalidParameter(err)
  438. }
  439. platform = &p
  440. }
  441. }
  442. if versions.LessThan(version, "1.42") {
  443. for _, m := range hostConfig.Mounts {
  444. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  445. if bo := m.BindOptions; bo != nil {
  446. bo.CreateMountpoint = false
  447. }
  448. // These combinations are invalid, but weren't validated in API < 1.42.
  449. // We reset them here, so that validation doesn't produce an error.
  450. if o := m.VolumeOptions; o != nil && m.Type != mount.TypeVolume {
  451. m.VolumeOptions = nil
  452. }
  453. if o := m.TmpfsOptions; o != nil && m.Type != mount.TypeTmpfs {
  454. m.TmpfsOptions = nil
  455. }
  456. if bo := m.BindOptions; bo != nil {
  457. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  458. bo.CreateMountpoint = false
  459. }
  460. }
  461. if runtime.GOOS == "linux" {
  462. // ConsoleSize is not respected by Linux daemon before API 1.42
  463. hostConfig.ConsoleSize = [2]uint{0, 0}
  464. }
  465. }
  466. if 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 versions.LessThan(version, "1.43") {
  482. // Ignore Annotations because it was added in API v1.43.
  483. hostConfig.Annotations = nil
  484. }
  485. defaultReadOnlyNonRecursive := false
  486. if versions.LessThan(version, "1.44") {
  487. if config.Healthcheck != nil {
  488. // StartInterval was added in API 1.44
  489. config.Healthcheck.StartInterval = 0
  490. }
  491. // Set ReadOnlyNonRecursive to true because it was added in API 1.44
  492. // Before that all read-only mounts were non-recursive.
  493. // Keep that behavior for clients on older APIs.
  494. defaultReadOnlyNonRecursive = true
  495. for _, m := range hostConfig.Mounts {
  496. if m.Type == mount.TypeBind {
  497. if m.BindOptions != nil && m.BindOptions.ReadOnlyForceRecursive {
  498. // NOTE: that technically this is a breaking change for older
  499. // API versions, and we should ignore the new field.
  500. // However, this option may be incorrectly set by a client with
  501. // the expectation that the failing to apply recursive read-only
  502. // is enforced, so we decided to produce an error instead,
  503. // instead of silently ignoring.
  504. return errdefs.InvalidParameter(errors.New("BindOptions.ReadOnlyForceRecursive needs API v1.44 or newer"))
  505. }
  506. }
  507. }
  508. // Creating a container connected to several networks is not supported until v1.44.
  509. if len(networkingConfig.EndpointsConfig) > 1 {
  510. l := make([]string, 0, len(networkingConfig.EndpointsConfig))
  511. for k := range networkingConfig.EndpointsConfig {
  512. l = append(l, k)
  513. }
  514. return errdefs.InvalidParameter(errors.Errorf("Container cannot be created with multiple network endpoints: %s", strings.Join(l, ", ")))
  515. }
  516. }
  517. if versions.LessThan(version, "1.45") {
  518. for _, m := range hostConfig.Mounts {
  519. if m.VolumeOptions != nil && m.VolumeOptions.Subpath != "" {
  520. return errdefs.InvalidParameter(errors.New("VolumeOptions.Subpath needs API v1.45 or newer"))
  521. }
  522. }
  523. }
  524. var warnings []string
  525. if warn, err := handleMACAddressBC(config, hostConfig, networkingConfig, version); err != nil {
  526. return err
  527. } else if warn != "" {
  528. warnings = append(warnings, warn)
  529. }
  530. if hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  531. // Don't set a limit if either no limit was specified, or "unlimited" was
  532. // explicitly set.
  533. // Both `0` and `-1` are accepted as "unlimited", and historically any
  534. // negative value was accepted, so treat those as "unlimited" as well.
  535. hostConfig.PidsLimit = nil
  536. }
  537. ccr, err := s.backend.ContainerCreate(ctx, backend.ContainerCreateConfig{
  538. Name: name,
  539. Config: config,
  540. HostConfig: hostConfig,
  541. NetworkingConfig: networkingConfig,
  542. Platform: platform,
  543. DefaultReadOnlyNonRecursive: defaultReadOnlyNonRecursive,
  544. })
  545. if err != nil {
  546. return err
  547. }
  548. ccr.Warnings = append(ccr.Warnings, warnings...)
  549. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  550. }
  551. // handleMACAddressBC takes care of backward-compatibility for the container-wide MAC address by mutating the
  552. // networkingConfig to set the endpoint-specific MACAddress field introduced in API v1.44. It returns a warning message
  553. // or an error if the container-wide field was specified for API >= v1.44.
  554. func handleMACAddressBC(config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, version string) (string, error) {
  555. deprecatedMacAddress := config.MacAddress //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44.
  556. // For older versions of the API, migrate the container-wide MAC address to EndpointsConfig.
  557. if versions.LessThan(version, "1.44") {
  558. if deprecatedMacAddress == "" {
  559. // If a MAC address is supplied in EndpointsConfig, discard it because the old API
  560. // would have ignored it.
  561. for _, ep := range networkingConfig.EndpointsConfig {
  562. ep.MacAddress = ""
  563. }
  564. return "", nil
  565. }
  566. if !hostConfig.NetworkMode.IsBridge() && !hostConfig.NetworkMode.IsUserDefined() {
  567. return "", runconfig.ErrConflictContainerNetworkAndMac
  568. }
  569. // There cannot be more than one entry in EndpointsConfig with API < 1.44.
  570. // If there's no EndpointsConfig, create a place to store the configured address. It is
  571. // safe to use NetworkMode as the network name, whether it's a name or id/short-id, as
  572. // it will be normalised later and there is no other EndpointSettings object that might
  573. // refer to this network/endpoint.
  574. if len(networkingConfig.EndpointsConfig) == 0 {
  575. nwName := hostConfig.NetworkMode.NetworkName()
  576. networkingConfig.EndpointsConfig[nwName] = &network.EndpointSettings{}
  577. }
  578. // There's exactly one network in EndpointsConfig, either from the API or just-created.
  579. // Migrate the container-wide setting to it.
  580. // No need to check for a match between NetworkMode and the names/ids in EndpointsConfig,
  581. // the old version of the API would have applied the address to this network anyway.
  582. for _, ep := range networkingConfig.EndpointsConfig {
  583. ep.MacAddress = deprecatedMacAddress
  584. }
  585. return "", nil
  586. }
  587. // The container-wide MacAddress parameter is deprecated and should now be specified in EndpointsConfig.
  588. if deprecatedMacAddress == "" {
  589. return "", nil
  590. }
  591. var warning string
  592. if hostConfig.NetworkMode.IsBridge() || hostConfig.NetworkMode.IsUserDefined() {
  593. nwName := hostConfig.NetworkMode.NetworkName()
  594. // If there's no endpoint config, create a place to store the configured address.
  595. if len(networkingConfig.EndpointsConfig) == 0 {
  596. networkingConfig.EndpointsConfig[nwName] = &network.EndpointSettings{
  597. MacAddress: deprecatedMacAddress,
  598. }
  599. } else {
  600. // There is existing endpoint config - if it's not indexed by NetworkMode.Name(), we
  601. // can't tell which network the container-wide settings was intended for. NetworkMode,
  602. // the keys in EndpointsConfig and the NetworkID in EndpointsConfig may mix network
  603. // name/id/short-id. It's not safe to create EndpointsConfig under the NetworkMode
  604. // name to store the container-wide MAC address, because that may result in two sets
  605. // of EndpointsConfig for the same network and one set will be discarded later. So,
  606. // reject the request ...
  607. ep, ok := networkingConfig.EndpointsConfig[nwName]
  608. if !ok {
  609. return "", errdefs.InvalidParameter(errors.New("if a container-wide MAC address is supplied, HostConfig.NetworkMode must match the identity of a network in NetworkSettings.Networks"))
  610. }
  611. // ep is the endpoint that needs the container-wide MAC address; migrate the address
  612. // to it, or bail out if there's a mismatch.
  613. if ep.MacAddress == "" {
  614. ep.MacAddress = deprecatedMacAddress
  615. } else if ep.MacAddress != deprecatedMacAddress {
  616. return "", errdefs.InvalidParameter(errors.New("the container-wide MAC address must match the endpoint-specific MAC address for the main network, or be left empty"))
  617. }
  618. }
  619. }
  620. warning = "The container-wide MacAddress field is now deprecated. It should be specified in EndpointsConfig instead."
  621. config.MacAddress = "" //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44.
  622. return warning, nil
  623. }
  624. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  625. if err := httputils.ParseForm(r); err != nil {
  626. return err
  627. }
  628. name := vars["name"]
  629. config := &backend.ContainerRmConfig{
  630. ForceRemove: httputils.BoolValue(r, "force"),
  631. RemoveVolume: httputils.BoolValue(r, "v"),
  632. RemoveLink: httputils.BoolValue(r, "link"),
  633. }
  634. if err := s.backend.ContainerRm(name, config); err != nil {
  635. return err
  636. }
  637. w.WriteHeader(http.StatusNoContent)
  638. return nil
  639. }
  640. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  641. if err := httputils.ParseForm(r); err != nil {
  642. return err
  643. }
  644. height, err := strconv.Atoi(r.Form.Get("h"))
  645. if err != nil {
  646. return errdefs.InvalidParameter(err)
  647. }
  648. width, err := strconv.Atoi(r.Form.Get("w"))
  649. if err != nil {
  650. return errdefs.InvalidParameter(err)
  651. }
  652. return s.backend.ContainerResize(vars["name"], height, width)
  653. }
  654. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  655. err := httputils.ParseForm(r)
  656. if err != nil {
  657. return err
  658. }
  659. containerName := vars["name"]
  660. _, upgrade := r.Header["Upgrade"]
  661. detachKeys := r.FormValue("detachKeys")
  662. hijacker, ok := w.(http.Hijacker)
  663. if !ok {
  664. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  665. }
  666. contentType := types.MediaTypeRawStream
  667. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  668. conn, _, err := hijacker.Hijack()
  669. if err != nil {
  670. return nil, nil, nil, err
  671. }
  672. // set raw mode
  673. conn.Write([]byte{})
  674. if upgrade {
  675. if multiplexed && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  676. contentType = types.MediaTypeMultiplexedStream
  677. }
  678. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: "+contentType+"\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  679. } else {
  680. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  681. }
  682. closer := func() error {
  683. httputils.CloseStreams(conn)
  684. return nil
  685. }
  686. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  687. }
  688. attachConfig := &backend.ContainerAttachConfig{
  689. GetStreams: setupStreams,
  690. UseStdin: httputils.BoolValue(r, "stdin"),
  691. UseStdout: httputils.BoolValue(r, "stdout"),
  692. UseStderr: httputils.BoolValue(r, "stderr"),
  693. Logs: httputils.BoolValue(r, "logs"),
  694. Stream: httputils.BoolValue(r, "stream"),
  695. DetachKeys: detachKeys,
  696. MuxStreams: true,
  697. }
  698. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  699. log.G(ctx).WithError(err).Errorf("Handler for %s %s returned error", r.Method, r.URL.Path)
  700. // Remember to close stream if error happens
  701. conn, _, errHijack := hijacker.Hijack()
  702. if errHijack != nil {
  703. log.G(ctx).WithError(err).Errorf("Handler for %s %s: unable to close stream; error when hijacking connection", r.Method, r.URL.Path)
  704. } else {
  705. statusCode := httpstatus.FromError(err)
  706. statusText := http.StatusText(statusCode)
  707. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: %s\r\n\r\n%s\r\n", statusCode, statusText, contentType, err.Error())
  708. httputils.CloseStreams(conn)
  709. }
  710. }
  711. return nil
  712. }
  713. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  714. if err := httputils.ParseForm(r); err != nil {
  715. return err
  716. }
  717. containerName := vars["name"]
  718. var err error
  719. detachKeys := r.FormValue("detachKeys")
  720. done := make(chan struct{})
  721. started := make(chan struct{})
  722. version := httputils.VersionFromContext(ctx)
  723. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  724. wsChan := make(chan *websocket.Conn)
  725. h := func(conn *websocket.Conn) {
  726. wsChan <- conn
  727. <-done
  728. }
  729. srv := websocket.Server{Handler: h, Handshake: nil}
  730. go func() {
  731. close(started)
  732. srv.ServeHTTP(w, r)
  733. }()
  734. conn := <-wsChan
  735. // In case version 1.28 and above, a binary frame will be sent.
  736. // See 28176 for details.
  737. if versions.GreaterThanOrEqualTo(version, "1.28") {
  738. conn.PayloadType = websocket.BinaryFrame
  739. }
  740. return conn, conn, conn, nil
  741. }
  742. useStdin, useStdout, useStderr := true, true, true
  743. if versions.GreaterThanOrEqualTo(version, "1.42") {
  744. useStdin = httputils.BoolValue(r, "stdin")
  745. useStdout = httputils.BoolValue(r, "stdout")
  746. useStderr = httputils.BoolValue(r, "stderr")
  747. }
  748. attachConfig := &backend.ContainerAttachConfig{
  749. GetStreams: setupStreams,
  750. UseStdin: useStdin,
  751. UseStdout: useStdout,
  752. UseStderr: useStderr,
  753. Logs: httputils.BoolValue(r, "logs"),
  754. Stream: httputils.BoolValue(r, "stream"),
  755. DetachKeys: detachKeys,
  756. MuxStreams: false, // never multiplex, as we rely on websocket to manage distinct streams
  757. }
  758. err = s.backend.ContainerAttach(containerName, attachConfig)
  759. close(done)
  760. select {
  761. case <-started:
  762. if err != nil {
  763. log.G(ctx).Errorf("Error attaching websocket: %s", err)
  764. } else {
  765. log.G(ctx).Debug("websocket connection was closed by client")
  766. }
  767. return nil
  768. default:
  769. }
  770. return err
  771. }
  772. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  773. if err := httputils.ParseForm(r); err != nil {
  774. return err
  775. }
  776. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  777. if err != nil {
  778. return err
  779. }
  780. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  781. if err != nil {
  782. return err
  783. }
  784. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  785. }