container_routes.go 18 KB

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