container_routes.go 16 KB

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