container_routes.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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/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. "github.com/docker/docker/pkg/ioutils"
  18. "github.com/docker/docker/pkg/signal"
  19. "github.com/docker/docker/pkg/stdcopy"
  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 := &backend.ContainerLogsConfig{
  81. ContainerLogsOptions: 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. OutStream: w,
  91. }
  92. chStarted := make(chan struct{})
  93. if err := s.backend.ContainerLogs(ctx, containerName, logsConfig, chStarted); err != nil {
  94. select {
  95. case <-chStarted:
  96. // The client may be expecting all of the data we're sending to
  97. // be multiplexed, so mux it through the Systemerr stream, which
  98. // will cause the client to throw an error when demuxing
  99. stdwriter := stdcopy.NewStdWriter(logsConfig.OutStream, stdcopy.Systemerr)
  100. fmt.Fprintf(stdwriter, "Error running logs job: %v\n", err)
  101. default:
  102. return err
  103. }
  104. }
  105. return nil
  106. }
  107. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  108. return s.backend.ContainerExport(vars["name"], w)
  109. }
  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 validationError{fmt.Errorf("starting container with non-empty request body was deprecated since v1.10 and removed in v1.12")}
  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. type errContainerIsRunning interface {
  163. ContainerIsRunning() bool
  164. }
  165. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  166. if err := httputils.ParseForm(r); err != nil {
  167. return err
  168. }
  169. var sig syscall.Signal
  170. name := vars["name"]
  171. // If we have a signal, look at it. Otherwise, do nothing
  172. if sigStr := r.Form.Get("signal"); sigStr != "" {
  173. var err error
  174. if sig, err = signal.ParseSignal(sigStr); err != nil {
  175. return err
  176. }
  177. }
  178. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  179. var isStopped bool
  180. if e, ok := err.(errContainerIsRunning); ok {
  181. isStopped = !e.ContainerIsRunning()
  182. }
  183. // Return error that's not caused because the container is stopped.
  184. // Return error if the container is not running and the api is >= 1.20
  185. // to keep backwards compatibility.
  186. version := httputils.VersionFromContext(ctx)
  187. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  188. return fmt.Errorf("Cannot kill container %s: %v", name, err)
  189. }
  190. }
  191. w.WriteHeader(http.StatusNoContent)
  192. return nil
  193. }
  194. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  195. if err := httputils.ParseForm(r); err != nil {
  196. return err
  197. }
  198. var seconds *int
  199. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  200. valSeconds, err := strconv.Atoi(tmpSeconds)
  201. if err != nil {
  202. return err
  203. }
  204. seconds = &valSeconds
  205. }
  206. if err := s.backend.ContainerRestart(vars["name"], seconds); err != nil {
  207. return err
  208. }
  209. w.WriteHeader(http.StatusNoContent)
  210. return nil
  211. }
  212. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  213. if err := httputils.ParseForm(r); err != nil {
  214. return err
  215. }
  216. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  217. return err
  218. }
  219. w.WriteHeader(http.StatusNoContent)
  220. return nil
  221. }
  222. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  223. if err := httputils.ParseForm(r); err != nil {
  224. return err
  225. }
  226. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  227. return err
  228. }
  229. w.WriteHeader(http.StatusNoContent)
  230. return nil
  231. }
  232. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  233. status, err := s.backend.ContainerWait(vars["name"], -1*time.Second)
  234. if err != nil {
  235. return err
  236. }
  237. return httputils.WriteJSON(w, http.StatusOK, &container.ContainerWaitOKBody{
  238. StatusCode: int64(status),
  239. })
  240. }
  241. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  242. changes, err := s.backend.ContainerChanges(vars["name"])
  243. if err != nil {
  244. return err
  245. }
  246. return httputils.WriteJSON(w, http.StatusOK, changes)
  247. }
  248. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  249. if err := httputils.ParseForm(r); err != nil {
  250. return err
  251. }
  252. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  253. if err != nil {
  254. return err
  255. }
  256. return httputils.WriteJSON(w, http.StatusOK, procList)
  257. }
  258. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  259. if err := httputils.ParseForm(r); err != nil {
  260. return err
  261. }
  262. name := vars["name"]
  263. newName := r.Form.Get("name")
  264. if err := s.backend.ContainerRename(name, newName); err != nil {
  265. return err
  266. }
  267. w.WriteHeader(http.StatusNoContent)
  268. return nil
  269. }
  270. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  271. if err := httputils.ParseForm(r); err != nil {
  272. return err
  273. }
  274. if err := httputils.CheckForJSON(r); err != nil {
  275. return err
  276. }
  277. var updateConfig container.UpdateConfig
  278. decoder := json.NewDecoder(r.Body)
  279. if err := decoder.Decode(&updateConfig); err != nil {
  280. return err
  281. }
  282. hostConfig := &container.HostConfig{
  283. Resources: updateConfig.Resources,
  284. RestartPolicy: updateConfig.RestartPolicy,
  285. }
  286. name := vars["name"]
  287. resp, err := s.backend.ContainerUpdate(name, hostConfig)
  288. if err != nil {
  289. return err
  290. }
  291. return httputils.WriteJSON(w, http.StatusOK, resp)
  292. }
  293. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  294. if err := httputils.ParseForm(r); err != nil {
  295. return err
  296. }
  297. if err := httputils.CheckForJSON(r); err != nil {
  298. return err
  299. }
  300. name := r.Form.Get("name")
  301. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  302. if err != nil {
  303. return err
  304. }
  305. version := httputils.VersionFromContext(ctx)
  306. adjustCPUShares := versions.LessThan(version, "1.19")
  307. // When using API 1.24 and under, the client is responsible for removing the container
  308. if hostConfig != nil && versions.LessThan(version, "1.25") {
  309. hostConfig.AutoRemove = false
  310. }
  311. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  312. Name: name,
  313. Config: config,
  314. HostConfig: hostConfig,
  315. NetworkingConfig: networkingConfig,
  316. AdjustCPUShares: adjustCPUShares,
  317. })
  318. if err != nil {
  319. return err
  320. }
  321. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  322. }
  323. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  324. if err := httputils.ParseForm(r); err != nil {
  325. return err
  326. }
  327. name := vars["name"]
  328. config := &types.ContainerRmConfig{
  329. ForceRemove: httputils.BoolValue(r, "force"),
  330. RemoveVolume: httputils.BoolValue(r, "v"),
  331. RemoveLink: httputils.BoolValue(r, "link"),
  332. }
  333. if err := s.backend.ContainerRm(name, config); err != nil {
  334. return err
  335. }
  336. w.WriteHeader(http.StatusNoContent)
  337. return nil
  338. }
  339. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  340. if err := httputils.ParseForm(r); err != nil {
  341. return err
  342. }
  343. height, err := strconv.Atoi(r.Form.Get("h"))
  344. if err != nil {
  345. return err
  346. }
  347. width, err := strconv.Atoi(r.Form.Get("w"))
  348. if err != nil {
  349. return err
  350. }
  351. return s.backend.ContainerResize(vars["name"], height, width)
  352. }
  353. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  354. err := httputils.ParseForm(r)
  355. if err != nil {
  356. return err
  357. }
  358. containerName := vars["name"]
  359. _, upgrade := r.Header["Upgrade"]
  360. detachKeys := r.FormValue("detachKeys")
  361. hijacker, ok := w.(http.Hijacker)
  362. if !ok {
  363. return fmt.Errorf("error attaching to container %s, hijack connection missing", containerName)
  364. }
  365. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  366. conn, _, err := hijacker.Hijack()
  367. if err != nil {
  368. return nil, nil, nil, err
  369. }
  370. // set raw mode
  371. conn.Write([]byte{})
  372. if upgrade {
  373. 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")
  374. } else {
  375. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  376. }
  377. closer := func() error {
  378. httputils.CloseStreams(conn)
  379. return nil
  380. }
  381. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  382. }
  383. attachConfig := &backend.ContainerAttachConfig{
  384. GetStreams: setupStreams,
  385. UseStdin: httputils.BoolValue(r, "stdin"),
  386. UseStdout: httputils.BoolValue(r, "stdout"),
  387. UseStderr: httputils.BoolValue(r, "stderr"),
  388. Logs: httputils.BoolValue(r, "logs"),
  389. Stream: httputils.BoolValue(r, "stream"),
  390. DetachKeys: detachKeys,
  391. MuxStreams: true,
  392. }
  393. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  394. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  395. // Remember to close stream if error happens
  396. conn, _, errHijack := hijacker.Hijack()
  397. if errHijack == nil {
  398. statusCode := httputils.GetHTTPErrorStatusCode(err)
  399. statusText := http.StatusText(statusCode)
  400. 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())
  401. httputils.CloseStreams(conn)
  402. } else {
  403. logrus.Errorf("Error Hijacking: %v", err)
  404. }
  405. }
  406. return nil
  407. }
  408. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  409. if err := httputils.ParseForm(r); err != nil {
  410. return err
  411. }
  412. containerName := vars["name"]
  413. var err error
  414. detachKeys := r.FormValue("detachKeys")
  415. done := make(chan struct{})
  416. started := make(chan struct{})
  417. version := httputils.VersionFromContext(ctx)
  418. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  419. wsChan := make(chan *websocket.Conn)
  420. h := func(conn *websocket.Conn) {
  421. wsChan <- conn
  422. <-done
  423. }
  424. srv := websocket.Server{Handler: h, Handshake: nil}
  425. go func() {
  426. close(started)
  427. srv.ServeHTTP(w, r)
  428. }()
  429. conn := <-wsChan
  430. // In case version 1.28 and above, a binary frame will be sent.
  431. // See 28176 for details.
  432. if versions.GreaterThanOrEqualTo(version, "1.28") {
  433. conn.PayloadType = websocket.BinaryFrame
  434. }
  435. return conn, conn, conn, nil
  436. }
  437. attachConfig := &backend.ContainerAttachConfig{
  438. GetStreams: setupStreams,
  439. Logs: httputils.BoolValue(r, "logs"),
  440. Stream: httputils.BoolValue(r, "stream"),
  441. DetachKeys: detachKeys,
  442. UseStdin: true,
  443. UseStdout: true,
  444. UseStderr: true,
  445. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  446. }
  447. err = s.backend.ContainerAttach(containerName, attachConfig)
  448. close(done)
  449. select {
  450. case <-started:
  451. logrus.Errorf("Error attaching websocket: %s", err)
  452. return nil
  453. default:
  454. }
  455. return err
  456. }
  457. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  458. if err := httputils.ParseForm(r); err != nil {
  459. return err
  460. }
  461. pruneFilters, err := filters.FromParam(r.Form.Get("filters"))
  462. if err != nil {
  463. return err
  464. }
  465. pruneReport, err := s.backend.ContainersPrune(pruneFilters)
  466. if err != nil {
  467. return err
  468. }
  469. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  470. }