container_routes.go 17 KB

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