container_routes.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. package container
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "syscall"
  9. "github.com/docker/docker/api/server/httputils"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/backend"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/api/types/filters"
  14. "github.com/docker/docker/api/types/versions"
  15. containerpkg "github.com/docker/docker/container"
  16. "github.com/docker/docker/errdefs"
  17. "github.com/docker/docker/pkg/ioutils"
  18. "github.com/docker/docker/pkg/signal"
  19. "github.com/pkg/errors"
  20. "github.com/sirupsen/logrus"
  21. "golang.org/x/net/context"
  22. "golang.org/x/net/websocket"
  23. )
  24. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  25. if err := httputils.ParseForm(r); err != nil {
  26. return err
  27. }
  28. filter, err := filters.FromJSON(r.Form.Get("filters"))
  29. if err != nil {
  30. return err
  31. }
  32. config := &types.ContainerListOptions{
  33. All: httputils.BoolValue(r, "all"),
  34. Size: httputils.BoolValue(r, "size"),
  35. Since: r.Form.Get("since"),
  36. Before: r.Form.Get("before"),
  37. Filters: filter,
  38. }
  39. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  40. limit, err := strconv.Atoi(tmpLimit)
  41. if err != nil {
  42. return err
  43. }
  44. config.Limit = limit
  45. }
  46. containers, err := s.backend.Containers(config)
  47. if err != nil {
  48. return err
  49. }
  50. return httputils.WriteJSON(w, http.StatusOK, containers)
  51. }
  52. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  53. if err := httputils.ParseForm(r); err != nil {
  54. return err
  55. }
  56. stream := httputils.BoolValueOrDefault(r, "stream", true)
  57. if !stream {
  58. w.Header().Set("Content-Type", "application/json")
  59. }
  60. config := &backend.ContainerStatsConfig{
  61. Stream: stream,
  62. OutStream: w,
  63. Version: httputils.VersionFromContext(ctx),
  64. }
  65. return s.backend.ContainerStats(ctx, vars["name"], config)
  66. }
  67. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  68. if err := httputils.ParseForm(r); err != nil {
  69. return err
  70. }
  71. // Args are validated before the stream starts because when it starts we're
  72. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  73. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  74. // any error after the stream starts (i.e. container not found, wrong parameters)
  75. // with the appropriate status code.
  76. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  77. if !(stdout || stderr) {
  78. return errdefs.InvalidParameter(errors.New("Bad parameters: you must choose at least one stream"))
  79. }
  80. containerName := vars["name"]
  81. logsConfig := &types.ContainerLogsOptions{
  82. Follow: httputils.BoolValue(r, "follow"),
  83. Timestamps: httputils.BoolValue(r, "timestamps"),
  84. Since: r.Form.Get("since"),
  85. Until: r.Form.Get("until"),
  86. Tail: r.Form.Get("tail"),
  87. ShowStdout: stdout,
  88. ShowStderr: stderr,
  89. Details: httputils.BoolValue(r, "details"),
  90. }
  91. msgs, tty, err := s.backend.ContainerLogs(ctx, containerName, logsConfig)
  92. if err != nil {
  93. return err
  94. }
  95. // if has a tty, we're not muxing streams. if it doesn't, we are. simple.
  96. // this is the point of no return for writing a response. once we call
  97. // WriteLogStream, the response has been started and errors will be
  98. // returned in band by WriteLogStream
  99. httputils.WriteLogStream(ctx, w, msgs, logsConfig, !tty)
  100. return nil
  101. }
  102. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  103. return s.backend.ContainerExport(vars["name"], w)
  104. }
  105. type bodyOnStartError struct{}
  106. func (bodyOnStartError) Error() string {
  107. return "starting container with non-empty request body was deprecated since API v1.22 and removed in v1.24"
  108. }
  109. func (bodyOnStartError) InvalidParameter() {}
  110. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  111. // If contentLength is -1, we can assumed chunked encoding
  112. // or more technically that the length is unknown
  113. // https://golang.org/src/pkg/net/http/request.go#L139
  114. // net/http otherwise seems to swallow any headers related to chunked encoding
  115. // including r.TransferEncoding
  116. // allow a nil body for backwards compatibility
  117. version := httputils.VersionFromContext(ctx)
  118. var hostConfig *container.HostConfig
  119. // A non-nil json object is at least 7 characters.
  120. if r.ContentLength > 7 || r.ContentLength == -1 {
  121. if versions.GreaterThanOrEqualTo(version, "1.24") {
  122. return bodyOnStartError{}
  123. }
  124. if err := httputils.CheckForJSON(r); err != nil {
  125. return err
  126. }
  127. c, err := s.decoder.DecodeHostConfig(r.Body)
  128. if err != nil {
  129. return err
  130. }
  131. hostConfig = c
  132. }
  133. if err := httputils.ParseForm(r); err != nil {
  134. return err
  135. }
  136. checkpoint := r.Form.Get("checkpoint")
  137. checkpointDir := r.Form.Get("checkpoint-dir")
  138. if err := s.backend.ContainerStart(vars["name"], hostConfig, checkpoint, checkpointDir); err != nil {
  139. return err
  140. }
  141. w.WriteHeader(http.StatusNoContent)
  142. return nil
  143. }
  144. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  145. if err := httputils.ParseForm(r); err != nil {
  146. return err
  147. }
  148. var seconds *int
  149. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  150. valSeconds, err := strconv.Atoi(tmpSeconds)
  151. if err != nil {
  152. return err
  153. }
  154. seconds = &valSeconds
  155. }
  156. if err := s.backend.ContainerStop(vars["name"], seconds); err != nil {
  157. return err
  158. }
  159. w.WriteHeader(http.StatusNoContent)
  160. return nil
  161. }
  162. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  163. if err := httputils.ParseForm(r); err != nil {
  164. return err
  165. }
  166. var sig syscall.Signal
  167. name := vars["name"]
  168. // If we have a signal, look at it. Otherwise, do nothing
  169. if sigStr := r.Form.Get("signal"); sigStr != "" {
  170. var err error
  171. if sig, err = signal.ParseSignal(sigStr); err != nil {
  172. return errdefs.InvalidParameter(err)
  173. }
  174. }
  175. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  176. var isStopped bool
  177. if errdefs.IsConflict(err) {
  178. isStopped = true
  179. }
  180. // Return error that's not caused because the container is stopped.
  181. // Return error if the container is not running and the api is >= 1.20
  182. // to keep backwards compatibility.
  183. version := httputils.VersionFromContext(ctx)
  184. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  185. return errors.Wrapf(err, "Cannot kill container: %s", name)
  186. }
  187. }
  188. w.WriteHeader(http.StatusNoContent)
  189. return nil
  190. }
  191. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  192. if err := httputils.ParseForm(r); err != nil {
  193. return err
  194. }
  195. var seconds *int
  196. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  197. valSeconds, err := strconv.Atoi(tmpSeconds)
  198. if err != nil {
  199. return err
  200. }
  201. seconds = &valSeconds
  202. }
  203. if err := s.backend.ContainerRestart(vars["name"], seconds); err != nil {
  204. return err
  205. }
  206. w.WriteHeader(http.StatusNoContent)
  207. return nil
  208. }
  209. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  210. if err := httputils.ParseForm(r); err != nil {
  211. return err
  212. }
  213. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  214. return err
  215. }
  216. w.WriteHeader(http.StatusNoContent)
  217. return nil
  218. }
  219. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  220. if err := httputils.ParseForm(r); err != nil {
  221. return err
  222. }
  223. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  224. return err
  225. }
  226. w.WriteHeader(http.StatusNoContent)
  227. return nil
  228. }
  229. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  230. // Behavior changed in version 1.30 to handle wait condition and to
  231. // return headers immediately.
  232. version := httputils.VersionFromContext(ctx)
  233. legacyBehaviorPre130 := versions.LessThan(version, "1.30")
  234. legacyRemovalWaitPre134 := false
  235. // The wait condition defaults to "not-running".
  236. waitCondition := containerpkg.WaitConditionNotRunning
  237. if !legacyBehaviorPre130 {
  238. if err := httputils.ParseForm(r); err != nil {
  239. return err
  240. }
  241. switch container.WaitCondition(r.Form.Get("condition")) {
  242. case container.WaitConditionNextExit:
  243. waitCondition = containerpkg.WaitConditionNextExit
  244. case container.WaitConditionRemoved:
  245. waitCondition = containerpkg.WaitConditionRemoved
  246. legacyRemovalWaitPre134 = versions.LessThan(version, "1.34")
  247. }
  248. }
  249. // Note: the context should get canceled if the client closes the
  250. // connection since this handler has been wrapped by the
  251. // router.WithCancel() wrapper.
  252. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  253. if err != nil {
  254. return err
  255. }
  256. w.Header().Set("Content-Type", "application/json")
  257. if !legacyBehaviorPre130 {
  258. // Write response header immediately.
  259. w.WriteHeader(http.StatusOK)
  260. if flusher, ok := w.(http.Flusher); ok {
  261. flusher.Flush()
  262. }
  263. }
  264. // Block on the result of the wait operation.
  265. status := <-waitC
  266. // With API < 1.34, wait on WaitConditionRemoved did not return
  267. // in case container removal failed. The only way to report an
  268. // error back to the client is to not write anything (i.e. send
  269. // an empty response which will be treated as an error).
  270. if legacyRemovalWaitPre134 && status.Err() != nil {
  271. return nil
  272. }
  273. var waitError *container.ContainerWaitOKBodyError
  274. if status.Err() != nil {
  275. waitError = &container.ContainerWaitOKBodyError{Message: status.Err().Error()}
  276. }
  277. return json.NewEncoder(w).Encode(&container.ContainerWaitOKBody{
  278. StatusCode: int64(status.ExitCode()),
  279. Error: waitError,
  280. })
  281. }
  282. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  283. changes, err := s.backend.ContainerChanges(vars["name"])
  284. if err != nil {
  285. return err
  286. }
  287. return httputils.WriteJSON(w, http.StatusOK, changes)
  288. }
  289. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  290. if err := httputils.ParseForm(r); err != nil {
  291. return err
  292. }
  293. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  294. if err != nil {
  295. return err
  296. }
  297. return httputils.WriteJSON(w, http.StatusOK, procList)
  298. }
  299. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  300. if err := httputils.ParseForm(r); err != nil {
  301. return err
  302. }
  303. name := vars["name"]
  304. newName := r.Form.Get("name")
  305. if err := s.backend.ContainerRename(name, newName); err != nil {
  306. return err
  307. }
  308. w.WriteHeader(http.StatusNoContent)
  309. return nil
  310. }
  311. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  312. if err := httputils.ParseForm(r); err != nil {
  313. return err
  314. }
  315. if err := httputils.CheckForJSON(r); err != nil {
  316. return err
  317. }
  318. var updateConfig container.UpdateConfig
  319. decoder := json.NewDecoder(r.Body)
  320. if err := decoder.Decode(&updateConfig); err != nil {
  321. return err
  322. }
  323. hostConfig := &container.HostConfig{
  324. Resources: updateConfig.Resources,
  325. RestartPolicy: updateConfig.RestartPolicy,
  326. }
  327. name := vars["name"]
  328. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  329. if err != nil {
  330. return err
  331. }
  332. return httputils.WriteJSON(w, http.StatusOK, resp)
  333. }
  334. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  335. if err := httputils.ParseForm(r); err != nil {
  336. return err
  337. }
  338. if err := httputils.CheckForJSON(r); err != nil {
  339. return err
  340. }
  341. name := r.Form.Get("name")
  342. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  343. if err != nil {
  344. return err
  345. }
  346. version := httputils.VersionFromContext(ctx)
  347. adjustCPUShares := versions.LessThan(version, "1.19")
  348. // When using API 1.24 and under, the client is responsible for removing the container
  349. if hostConfig != nil && versions.LessThan(version, "1.25") {
  350. hostConfig.AutoRemove = false
  351. }
  352. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  353. Name: name,
  354. Config: config,
  355. HostConfig: hostConfig,
  356. NetworkingConfig: networkingConfig,
  357. AdjustCPUShares: adjustCPUShares,
  358. })
  359. if err != nil {
  360. return err
  361. }
  362. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  363. }
  364. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  365. if err := httputils.ParseForm(r); err != nil {
  366. return err
  367. }
  368. name := vars["name"]
  369. config := &types.ContainerRmConfig{
  370. ForceRemove: httputils.BoolValue(r, "force"),
  371. RemoveVolume: httputils.BoolValue(r, "v"),
  372. RemoveLink: httputils.BoolValue(r, "link"),
  373. }
  374. if err := s.backend.ContainerRm(name, config); err != nil {
  375. return err
  376. }
  377. w.WriteHeader(http.StatusNoContent)
  378. return nil
  379. }
  380. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  381. if err := httputils.ParseForm(r); err != nil {
  382. return err
  383. }
  384. height, err := strconv.Atoi(r.Form.Get("h"))
  385. if err != nil {
  386. return errdefs.InvalidParameter(err)
  387. }
  388. width, err := strconv.Atoi(r.Form.Get("w"))
  389. if err != nil {
  390. return errdefs.InvalidParameter(err)
  391. }
  392. return s.backend.ContainerResize(vars["name"], height, width)
  393. }
  394. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  395. err := httputils.ParseForm(r)
  396. if err != nil {
  397. return err
  398. }
  399. containerName := vars["name"]
  400. _, upgrade := r.Header["Upgrade"]
  401. detachKeys := r.FormValue("detachKeys")
  402. hijacker, ok := w.(http.Hijacker)
  403. if !ok {
  404. return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName))
  405. }
  406. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  407. conn, _, err := hijacker.Hijack()
  408. if err != nil {
  409. return nil, nil, nil, err
  410. }
  411. // set raw mode
  412. conn.Write([]byte{})
  413. if upgrade {
  414. fmt.Fprintf(conn, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  415. } else {
  416. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  417. }
  418. closer := func() error {
  419. httputils.CloseStreams(conn)
  420. return nil
  421. }
  422. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  423. }
  424. attachConfig := &backend.ContainerAttachConfig{
  425. GetStreams: setupStreams,
  426. UseStdin: httputils.BoolValue(r, "stdin"),
  427. UseStdout: httputils.BoolValue(r, "stdout"),
  428. UseStderr: httputils.BoolValue(r, "stderr"),
  429. Logs: httputils.BoolValue(r, "logs"),
  430. Stream: httputils.BoolValue(r, "stream"),
  431. DetachKeys: detachKeys,
  432. MuxStreams: true,
  433. }
  434. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  435. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  436. // Remember to close stream if error happens
  437. conn, _, errHijack := hijacker.Hijack()
  438. if errHijack == nil {
  439. statusCode := httputils.GetHTTPErrorStatusCode(err)
  440. statusText := http.StatusText(statusCode)
  441. fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n%s\r\n", statusCode, statusText, err.Error())
  442. httputils.CloseStreams(conn)
  443. } else {
  444. logrus.Errorf("Error Hijacking: %v", err)
  445. }
  446. }
  447. return nil
  448. }
  449. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  450. if err := httputils.ParseForm(r); err != nil {
  451. return err
  452. }
  453. containerName := vars["name"]
  454. var err error
  455. detachKeys := r.FormValue("detachKeys")
  456. done := make(chan struct{})
  457. started := make(chan struct{})
  458. version := httputils.VersionFromContext(ctx)
  459. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  460. wsChan := make(chan *websocket.Conn)
  461. h := func(conn *websocket.Conn) {
  462. wsChan <- conn
  463. <-done
  464. }
  465. srv := websocket.Server{Handler: h, Handshake: nil}
  466. go func() {
  467. close(started)
  468. srv.ServeHTTP(w, r)
  469. }()
  470. conn := <-wsChan
  471. // In case version 1.28 and above, a binary frame will be sent.
  472. // See 28176 for details.
  473. if versions.GreaterThanOrEqualTo(version, "1.28") {
  474. conn.PayloadType = websocket.BinaryFrame
  475. }
  476. return conn, conn, conn, nil
  477. }
  478. attachConfig := &backend.ContainerAttachConfig{
  479. GetStreams: setupStreams,
  480. Logs: httputils.BoolValue(r, "logs"),
  481. Stream: httputils.BoolValue(r, "stream"),
  482. DetachKeys: detachKeys,
  483. UseStdin: true,
  484. UseStdout: true,
  485. UseStderr: true,
  486. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  487. }
  488. err = s.backend.ContainerAttach(containerName, attachConfig)
  489. close(done)
  490. select {
  491. case <-started:
  492. if err != nil {
  493. logrus.Errorf("Error attaching websocket: %s", err)
  494. } else {
  495. logrus.Debug("websocket connection was closed by client")
  496. }
  497. return nil
  498. default:
  499. }
  500. return err
  501. }
  502. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  503. if err := httputils.ParseForm(r); err != nil {
  504. return err
  505. }
  506. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  507. if err != nil {
  508. return errdefs.InvalidParameter(err)
  509. }
  510. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  511. if err != nil {
  512. return err
  513. }
  514. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  515. }