container_routes.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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.FromParam(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. legacyBehavior := versions.LessThan(version, "1.30")
  233. // The wait condition defaults to "not-running".
  234. waitCondition := containerpkg.WaitConditionNotRunning
  235. if !legacyBehavior {
  236. if err := httputils.ParseForm(r); err != nil {
  237. return err
  238. }
  239. switch container.WaitCondition(r.Form.Get("condition")) {
  240. case container.WaitConditionNextExit:
  241. waitCondition = containerpkg.WaitConditionNextExit
  242. case container.WaitConditionRemoved:
  243. waitCondition = containerpkg.WaitConditionRemoved
  244. }
  245. }
  246. // Note: the context should get canceled if the client closes the
  247. // connection since this handler has been wrapped by the
  248. // router.WithCancel() wrapper.
  249. waitC, err := s.backend.ContainerWait(ctx, vars["name"], waitCondition)
  250. if err != nil {
  251. return err
  252. }
  253. w.Header().Set("Content-Type", "application/json")
  254. if !legacyBehavior {
  255. // Write response header immediately.
  256. w.WriteHeader(http.StatusOK)
  257. if flusher, ok := w.(http.Flusher); ok {
  258. flusher.Flush()
  259. }
  260. }
  261. // Block on the result of the wait operation.
  262. status := <-waitC
  263. return json.NewEncoder(w).Encode(&container.ContainerWaitOKBody{
  264. StatusCode: int64(status.ExitCode()),
  265. })
  266. }
  267. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  268. changes, err := s.backend.ContainerChanges(vars["name"])
  269. if err != nil {
  270. return err
  271. }
  272. return httputils.WriteJSON(w, http.StatusOK, changes)
  273. }
  274. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  275. if err := httputils.ParseForm(r); err != nil {
  276. return err
  277. }
  278. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  279. if err != nil {
  280. return err
  281. }
  282. return httputils.WriteJSON(w, http.StatusOK, procList)
  283. }
  284. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  285. if err := httputils.ParseForm(r); err != nil {
  286. return err
  287. }
  288. name := vars["name"]
  289. newName := r.Form.Get("name")
  290. if err := s.backend.ContainerRename(name, newName); err != nil {
  291. return err
  292. }
  293. w.WriteHeader(http.StatusNoContent)
  294. return nil
  295. }
  296. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  297. if err := httputils.ParseForm(r); err != nil {
  298. return err
  299. }
  300. if err := httputils.CheckForJSON(r); err != nil {
  301. return err
  302. }
  303. var updateConfig container.UpdateConfig
  304. decoder := json.NewDecoder(r.Body)
  305. if err := decoder.Decode(&updateConfig); err != nil {
  306. return err
  307. }
  308. hostConfig := &container.HostConfig{
  309. Resources: updateConfig.Resources,
  310. RestartPolicy: updateConfig.RestartPolicy,
  311. }
  312. name := vars["name"]
  313. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  314. if err != nil {
  315. return err
  316. }
  317. return httputils.WriteJSON(w, http.StatusOK, resp)
  318. }
  319. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  320. if err := httputils.ParseForm(r); err != nil {
  321. return err
  322. }
  323. if err := httputils.CheckForJSON(r); err != nil {
  324. return err
  325. }
  326. name := r.Form.Get("name")
  327. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  328. if err != nil {
  329. return err
  330. }
  331. version := httputils.VersionFromContext(ctx)
  332. adjustCPUShares := versions.LessThan(version, "1.19")
  333. // When using API 1.24 and under, the client is responsible for removing the container
  334. if hostConfig != nil && versions.LessThan(version, "1.25") {
  335. hostConfig.AutoRemove = false
  336. }
  337. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  338. Name: name,
  339. Config: config,
  340. HostConfig: hostConfig,
  341. NetworkingConfig: networkingConfig,
  342. AdjustCPUShares: adjustCPUShares,
  343. })
  344. if err != nil {
  345. return err
  346. }
  347. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  348. }
  349. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  350. if err := httputils.ParseForm(r); err != nil {
  351. return err
  352. }
  353. name := vars["name"]
  354. config := &types.ContainerRmConfig{
  355. ForceRemove: httputils.BoolValue(r, "force"),
  356. RemoveVolume: httputils.BoolValue(r, "v"),
  357. RemoveLink: httputils.BoolValue(r, "link"),
  358. }
  359. if err := s.backend.ContainerRm(name, config); err != nil {
  360. return err
  361. }
  362. w.WriteHeader(http.StatusNoContent)
  363. return nil
  364. }
  365. func (s *containerRouter) postContainersResize(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. height, err := strconv.Atoi(r.Form.Get("h"))
  370. if err != nil {
  371. return validationError{err}
  372. }
  373. width, err := strconv.Atoi(r.Form.Get("w"))
  374. if err != nil {
  375. return validationError{err}
  376. }
  377. return s.backend.ContainerResize(vars["name"], height, width)
  378. }
  379. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  380. err := httputils.ParseForm(r)
  381. if err != nil {
  382. return err
  383. }
  384. containerName := vars["name"]
  385. _, upgrade := r.Header["Upgrade"]
  386. detachKeys := r.FormValue("detachKeys")
  387. hijacker, ok := w.(http.Hijacker)
  388. if !ok {
  389. return validationError{errors.Errorf("error attaching to container %s, hijack connection missing", containerName)}
  390. }
  391. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  392. conn, _, err := hijacker.Hijack()
  393. if err != nil {
  394. return nil, nil, nil, err
  395. }
  396. // set raw mode
  397. conn.Write([]byte{})
  398. if upgrade {
  399. 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")
  400. } else {
  401. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  402. }
  403. closer := func() error {
  404. httputils.CloseStreams(conn)
  405. return nil
  406. }
  407. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  408. }
  409. attachConfig := &backend.ContainerAttachConfig{
  410. GetStreams: setupStreams,
  411. UseStdin: httputils.BoolValue(r, "stdin"),
  412. UseStdout: httputils.BoolValue(r, "stdout"),
  413. UseStderr: httputils.BoolValue(r, "stderr"),
  414. Logs: httputils.BoolValue(r, "logs"),
  415. Stream: httputils.BoolValue(r, "stream"),
  416. DetachKeys: detachKeys,
  417. MuxStreams: true,
  418. }
  419. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  420. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  421. // Remember to close stream if error happens
  422. conn, _, errHijack := hijacker.Hijack()
  423. if errHijack == nil {
  424. statusCode := httputils.GetHTTPErrorStatusCode(err)
  425. statusText := http.StatusText(statusCode)
  426. 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())
  427. httputils.CloseStreams(conn)
  428. } else {
  429. logrus.Errorf("Error Hijacking: %v", err)
  430. }
  431. }
  432. return nil
  433. }
  434. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  435. if err := httputils.ParseForm(r); err != nil {
  436. return err
  437. }
  438. containerName := vars["name"]
  439. var err error
  440. detachKeys := r.FormValue("detachKeys")
  441. done := make(chan struct{})
  442. started := make(chan struct{})
  443. version := httputils.VersionFromContext(ctx)
  444. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  445. wsChan := make(chan *websocket.Conn)
  446. h := func(conn *websocket.Conn) {
  447. wsChan <- conn
  448. <-done
  449. }
  450. srv := websocket.Server{Handler: h, Handshake: nil}
  451. go func() {
  452. close(started)
  453. srv.ServeHTTP(w, r)
  454. }()
  455. conn := <-wsChan
  456. // In case version 1.28 and above, a binary frame will be sent.
  457. // See 28176 for details.
  458. if versions.GreaterThanOrEqualTo(version, "1.28") {
  459. conn.PayloadType = websocket.BinaryFrame
  460. }
  461. return conn, conn, conn, nil
  462. }
  463. attachConfig := &backend.ContainerAttachConfig{
  464. GetStreams: setupStreams,
  465. Logs: httputils.BoolValue(r, "logs"),
  466. Stream: httputils.BoolValue(r, "stream"),
  467. DetachKeys: detachKeys,
  468. UseStdin: true,
  469. UseStdout: true,
  470. UseStderr: true,
  471. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  472. }
  473. err = s.backend.ContainerAttach(containerName, attachConfig)
  474. close(done)
  475. select {
  476. case <-started:
  477. logrus.Errorf("Error attaching websocket: %s", err)
  478. return nil
  479. default:
  480. }
  481. return err
  482. }
  483. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  484. if err := httputils.ParseForm(r); err != nil {
  485. return err
  486. }
  487. pruneFilters, err := filters.FromParam(r.Form.Get("filters"))
  488. if err != nil {
  489. return validationError{err}
  490. }
  491. pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters)
  492. if err != nil {
  493. return err
  494. }
  495. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  496. }