container_routes.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 hostConfig.NetworkMode == "" {
  387. hostConfig.NetworkMode = "default"
  388. }
  389. if networkingConfig == nil {
  390. networkingConfig = &network.NetworkingConfig{}
  391. }
  392. if networkingConfig.EndpointsConfig == nil {
  393. networkingConfig.EndpointsConfig = make(map[string]*network.EndpointSettings)
  394. }
  395. version := httputils.VersionFromContext(ctx)
  396. // When using API 1.24 and under, the client is responsible for removing the container
  397. if versions.LessThan(version, "1.25") {
  398. hostConfig.AutoRemove = false
  399. }
  400. if versions.LessThan(version, "1.40") {
  401. // Ignore BindOptions.NonRecursive because it was added in API 1.40.
  402. for _, m := range hostConfig.Mounts {
  403. if bo := m.BindOptions; bo != nil {
  404. bo.NonRecursive = false
  405. }
  406. }
  407. // Ignore KernelMemoryTCP because it was added in API 1.40.
  408. hostConfig.KernelMemoryTCP = 0
  409. // Older clients (API < 1.40) expects the default to be shareable, make them happy
  410. if hostConfig.IpcMode.IsEmpty() {
  411. hostConfig.IpcMode = container.IPCModeShareable
  412. }
  413. }
  414. if versions.LessThan(version, "1.41") {
  415. // Older clients expect the default to be "host" on cgroup v1 hosts
  416. if !s.cgroup2 && hostConfig.CgroupnsMode.IsEmpty() {
  417. hostConfig.CgroupnsMode = container.CgroupnsModeHost
  418. }
  419. }
  420. var platform *ocispec.Platform
  421. if versions.GreaterThanOrEqualTo(version, "1.41") {
  422. if v := r.Form.Get("platform"); v != "" {
  423. p, err := platforms.Parse(v)
  424. if err != nil {
  425. return errdefs.InvalidParameter(err)
  426. }
  427. platform = &p
  428. }
  429. }
  430. if versions.LessThan(version, "1.42") {
  431. for _, m := range hostConfig.Mounts {
  432. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  433. if bo := m.BindOptions; bo != nil {
  434. bo.CreateMountpoint = false
  435. }
  436. // These combinations are invalid, but weren't validated in API < 1.42.
  437. // We reset them here, so that validation doesn't produce an error.
  438. if o := m.VolumeOptions; o != nil && m.Type != mount.TypeVolume {
  439. m.VolumeOptions = nil
  440. }
  441. if o := m.TmpfsOptions; o != nil && m.Type != mount.TypeTmpfs {
  442. m.TmpfsOptions = nil
  443. }
  444. if bo := m.BindOptions; bo != nil {
  445. // Ignore BindOptions.CreateMountpoint because it was added in API 1.42.
  446. bo.CreateMountpoint = false
  447. }
  448. }
  449. if runtime.GOOS == "linux" {
  450. // ConsoleSize is not respected by Linux daemon before API 1.42
  451. hostConfig.ConsoleSize = [2]uint{0, 0}
  452. }
  453. }
  454. if versions.GreaterThanOrEqualTo(version, "1.42") {
  455. // Ignore KernelMemory removed in API 1.42.
  456. hostConfig.KernelMemory = 0
  457. for _, m := range hostConfig.Mounts {
  458. if o := m.VolumeOptions; o != nil && m.Type != mount.TypeVolume {
  459. return errdefs.InvalidParameter(fmt.Errorf("VolumeOptions must not be specified on mount type %q", m.Type))
  460. }
  461. if o := m.BindOptions; o != nil && m.Type != mount.TypeBind {
  462. return errdefs.InvalidParameter(fmt.Errorf("BindOptions must not be specified on mount type %q", m.Type))
  463. }
  464. if o := m.TmpfsOptions; o != nil && m.Type != mount.TypeTmpfs {
  465. return errdefs.InvalidParameter(fmt.Errorf("TmpfsOptions must not be specified on mount type %q", m.Type))
  466. }
  467. }
  468. }
  469. if versions.LessThan(version, "1.43") {
  470. // Ignore Annotations because it was added in API v1.43.
  471. hostConfig.Annotations = nil
  472. }
  473. if versions.LessThan(version, "1.44") {
  474. if config.Healthcheck != nil {
  475. // StartInterval was added in API 1.44
  476. config.Healthcheck.StartInterval = 0
  477. }
  478. for _, m := range hostConfig.Mounts {
  479. if m.BindOptions != nil {
  480. // Ignore ReadOnlyNonRecursive because it was added in API 1.44.
  481. m.BindOptions.ReadOnlyNonRecursive = false
  482. if m.BindOptions.ReadOnlyForceRecursive {
  483. return errdefs.InvalidParameter(errors.New("BindOptions.ReadOnlyForceRecursive needs API v1.44 or newer"))
  484. }
  485. }
  486. }
  487. // Creating a container connected to several networks is not supported until v1.44.
  488. if len(networkingConfig.EndpointsConfig) > 1 {
  489. l := make([]string, 0, len(networkingConfig.EndpointsConfig))
  490. for k := range networkingConfig.EndpointsConfig {
  491. l = append(l, k)
  492. }
  493. return errdefs.InvalidParameter(errors.Errorf("Container cannot be created with multiple network endpoints: %s", strings.Join(l, ", ")))
  494. }
  495. }
  496. if versions.LessThan(version, "1.45") {
  497. for _, m := range hostConfig.Mounts {
  498. if m.VolumeOptions != nil && m.VolumeOptions.Subpath != "" {
  499. return errdefs.InvalidParameter(errors.New("VolumeOptions.Subpath needs API v1.45 or newer"))
  500. }
  501. }
  502. }
  503. var warnings []string
  504. if warn, err := handleMACAddressBC(config, hostConfig, networkingConfig, version); err != nil {
  505. return err
  506. } else if warn != "" {
  507. warnings = append(warnings, warn)
  508. }
  509. if hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
  510. // Don't set a limit if either no limit was specified, or "unlimited" was
  511. // explicitly set.
  512. // Both `0` and `-1` are accepted as "unlimited", and historically any
  513. // negative value was accepted, so treat those as "unlimited" as well.
  514. hostConfig.PidsLimit = nil
  515. }
  516. ccr, err := s.backend.ContainerCreate(ctx, backend.ContainerCreateConfig{
  517. Name: name,
  518. Config: config,
  519. HostConfig: hostConfig,
  520. NetworkingConfig: networkingConfig,
  521. Platform: platform,
  522. })
  523. if err != nil {
  524. return err
  525. }
  526. ccr.Warnings = append(ccr.Warnings, warnings...)
  527. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  528. }
  529. // handleMACAddressBC takes care of backward-compatibility for the container-wide MAC address by mutating the
  530. // networkingConfig to set the endpoint-specific MACAddress field introduced in API v1.44. It returns a warning message
  531. // or an error if the container-wide field was specified for API >= v1.44.
  532. func handleMACAddressBC(config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, version string) (string, error) {
  533. if config.MacAddress == "" { //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44.
  534. return "", nil
  535. }
  536. deprecatedMacAddress := config.MacAddress //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44.
  537. if versions.LessThan(version, "1.44") {
  538. // The container-wide MacAddress parameter is deprecated and should now be specified in EndpointsConfig.
  539. if hostConfig.NetworkMode.IsDefault() || hostConfig.NetworkMode.IsBridge() || hostConfig.NetworkMode.IsUserDefined() {
  540. nwName := hostConfig.NetworkMode.NetworkName()
  541. if _, ok := networkingConfig.EndpointsConfig[nwName]; !ok {
  542. networkingConfig.EndpointsConfig[nwName] = &network.EndpointSettings{}
  543. }
  544. // Overwrite the config: either the endpoint's MacAddress was set by the user on API < v1.44, which
  545. // must be ignored, or migrate the top-level MacAddress to the endpoint's config.
  546. networkingConfig.EndpointsConfig[nwName].MacAddress = deprecatedMacAddress
  547. }
  548. if !hostConfig.NetworkMode.IsDefault() && !hostConfig.NetworkMode.IsBridge() && !hostConfig.NetworkMode.IsUserDefined() {
  549. return "", runconfig.ErrConflictContainerNetworkAndMac
  550. }
  551. return "", nil
  552. }
  553. var warning string
  554. if hostConfig.NetworkMode.IsDefault() || hostConfig.NetworkMode.IsBridge() || hostConfig.NetworkMode.IsUserDefined() {
  555. nwName := hostConfig.NetworkMode.NetworkName()
  556. if _, ok := networkingConfig.EndpointsConfig[nwName]; !ok {
  557. networkingConfig.EndpointsConfig[nwName] = &network.EndpointSettings{}
  558. }
  559. ep := networkingConfig.EndpointsConfig[nwName]
  560. if ep.MacAddress == "" {
  561. ep.MacAddress = deprecatedMacAddress
  562. } else if ep.MacAddress != deprecatedMacAddress {
  563. return "", errdefs.InvalidParameter(errors.New("the container-wide MAC address should match the endpoint-specific MAC address for the main network or should be left empty"))
  564. }
  565. }
  566. warning = "The container-wide MacAddress field is now deprecated. It should be specified in EndpointsConfig instead."
  567. config.MacAddress = "" //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44.
  568. return warning, nil
  569. }
  570. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  571. if err := httputils.ParseForm(r); err != nil {
  572. return err
  573. }
  574. name := vars["name"]
  575. config := &backend.ContainerRmConfig{
  576. ForceRemove: httputils.BoolValue(r, "force"),
  577. RemoveVolume: httputils.BoolValue(r, "v"),
  578. RemoveLink: httputils.BoolValue(r, "link"),
  579. }
  580. if err := s.backend.ContainerRm(name, config); err != nil {
  581. return err
  582. }
  583. w.WriteHeader(http.StatusNoContent)
  584. return nil
  585. }
  586. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  587. if err := httputils.ParseForm(r); err != nil {
  588. return err
  589. }
  590. height, err := strconv.Atoi(r.Form.Get("h"))
  591. if err != nil {
  592. return errdefs.InvalidParameter(err)
  593. }
  594. width, err := strconv.Atoi(r.Form.Get("w"))
  595. if err != nil {
  596. return errdefs.InvalidParameter(err)
  597. }
  598. return s.backend.ContainerResize(vars["name"], height, width)
  599. }
  600. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  601. err := httputils.ParseForm(r)
  602. if err != nil {
  603. return err
  604. }
  605. containerName := vars["name"]
  606. _, upgrade := r.Header["Upgrade"]
  607. detachKeys := r.FormValue("detachKeys")
  608. hijacker, ok := w.(http.Hijacker)
  609. if !ok {
  610. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  611. }
  612. contentType := types.MediaTypeRawStream
  613. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  614. conn, _, err := hijacker.Hijack()
  615. if err != nil {
  616. return nil, nil, nil, err
  617. }
  618. // set raw mode
  619. conn.Write([]byte{})
  620. if upgrade {
  621. if multiplexed && versions.GreaterThanOrEqualTo(httputils.VersionFromContext(ctx), "1.42") {
  622. contentType = types.MediaTypeMultiplexedStream
  623. }
  624. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: "+contentType+"\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  625. } else {
  626. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  627. }
  628. closer := func() error {
  629. httputils.CloseStreams(conn)
  630. return nil
  631. }
  632. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  633. }
  634. attachConfig := &backend.ContainerAttachConfig{
  635. GetStreams: setupStreams,
  636. UseStdin: httputils.BoolValue(r, "stdin"),
  637. UseStdout: httputils.BoolValue(r, "stdout"),
  638. UseStderr: httputils.BoolValue(r, "stderr"),
  639. Logs: httputils.BoolValue(r, "logs"),
  640. Stream: httputils.BoolValue(r, "stream"),
  641. DetachKeys: detachKeys,
  642. MuxStreams: true,
  643. }
  644. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  645. log.G(ctx).WithError(err).Errorf("Handler for %s %s returned error", r.Method, r.URL.Path)
  646. // Remember to close stream if error happens
  647. conn, _, errHijack := hijacker.Hijack()
  648. if errHijack != nil {
  649. log.G(ctx).WithError(err).Errorf("Handler for %s %s: unable to close stream; error when hijacking connection", r.Method, r.URL.Path)
  650. } else {
  651. statusCode := httpstatus.FromError(err)
  652. statusText := http.StatusText(statusCode)
  653. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: %s\r\n\r\n%s\r\n", statusCode, statusText, contentType, err.Error())
  654. httputils.CloseStreams(conn)
  655. }
  656. }
  657. return nil
  658. }
  659. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  660. if err := httputils.ParseForm(r); err != nil {
  661. return err
  662. }
  663. containerName := vars["name"]
  664. var err error
  665. detachKeys := r.FormValue("detachKeys")
  666. done := make(chan struct{})
  667. started := make(chan struct{})
  668. version := httputils.VersionFromContext(ctx)
  669. setupStreams := func(multiplexed bool) (io.ReadCloser, io.Writer, io.Writer, error) {
  670. wsChan := make(chan *websocket.Conn)
  671. h := func(conn *websocket.Conn) {
  672. wsChan <- conn
  673. <-done
  674. }
  675. srv := websocket.Server{Handler: h, Handshake: nil}
  676. go func() {
  677. close(started)
  678. srv.ServeHTTP(w, r)
  679. }()
  680. conn := <-wsChan
  681. // In case version 1.28 and above, a binary frame will be sent.
  682. // See 28176 for details.
  683. if versions.GreaterThanOrEqualTo(version, "1.28") {
  684. conn.PayloadType = websocket.BinaryFrame
  685. }
  686. return conn, conn, conn, nil
  687. }
  688. useStdin, useStdout, useStderr := true, true, true
  689. if versions.GreaterThanOrEqualTo(version, "1.42") {
  690. useStdin = httputils.BoolValue(r, "stdin")
  691. useStdout = httputils.BoolValue(r, "stdout")
  692. useStderr = httputils.BoolValue(r, "stderr")
  693. }
  694. attachConfig := &backend.ContainerAttachConfig{
  695. GetStreams: setupStreams,
  696. UseStdin: useStdin,
  697. UseStdout: useStdout,
  698. UseStderr: useStderr,
  699. Logs: httputils.BoolValue(r, "logs"),
  700. Stream: httputils.BoolValue(r, "stream"),
  701. DetachKeys: detachKeys,
  702. MuxStreams: false, // never multiplex, as we rely on websocket to manage distinct streams
  703. }
  704. err = s.backend.ContainerAttach(containerName, attachConfig)
  705. close(done)
  706. select {
  707. case <-started:
  708. if err != nil {
  709. log.G(ctx).Errorf("Error attaching websocket: %s", err)
  710. } else {
  711. log.G(ctx).Debug("websocket connection was closed by client")
  712. }
  713. return nil
  714. default:
  715. }
  716. return err
  717. }
  718. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  719. if err := httputils.ParseForm(r); err != nil {
  720. return err
  721. }
  722. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  723. if err != nil {
  724. return err
  725. }
  726. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  727. if err != nil {
  728. return err
  729. }
  730. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  731. }