container_routes.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. "golang.org/x/net/context"
  20. "golang.org/x/net/websocket"
  21. )
  22. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  23. if err := httputils.ParseForm(r); err != nil {
  24. return err
  25. }
  26. filter, err := filters.FromParam(r.Form.Get("filters"))
  27. if err != nil {
  28. return err
  29. }
  30. config := &types.ContainerListOptions{
  31. All: httputils.BoolValue(r, "all"),
  32. Size: httputils.BoolValue(r, "size"),
  33. Since: r.Form.Get("since"),
  34. Before: r.Form.Get("before"),
  35. Filters: filter,
  36. }
  37. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  38. limit, err := strconv.Atoi(tmpLimit)
  39. if err != nil {
  40. return err
  41. }
  42. config.Limit = limit
  43. }
  44. containers, err := s.backend.Containers(config)
  45. if err != nil {
  46. return err
  47. }
  48. return httputils.WriteJSON(w, http.StatusOK, containers)
  49. }
  50. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  51. if err := httputils.ParseForm(r); err != nil {
  52. return err
  53. }
  54. stream := httputils.BoolValueOrDefault(r, "stream", true)
  55. if !stream {
  56. w.Header().Set("Content-Type", "application/json")
  57. }
  58. config := &backend.ContainerStatsConfig{
  59. Stream: stream,
  60. OutStream: w,
  61. Version: string(httputils.VersionFromContext(ctx)),
  62. }
  63. return s.backend.ContainerStats(ctx, vars["name"], config)
  64. }
  65. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  66. if err := httputils.ParseForm(r); err != nil {
  67. return err
  68. }
  69. // Args are validated before the stream starts because when it starts we're
  70. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  71. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  72. // any error after the stream starts (i.e. container not found, wrong parameters)
  73. // with the appropriate status code.
  74. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  75. if !(stdout || stderr) {
  76. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  77. }
  78. containerName := vars["name"]
  79. logsConfig := &backend.ContainerLogsConfig{
  80. ContainerLogsOptions: 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. OutStream: w,
  90. }
  91. chStarted := make(chan struct{})
  92. if err := s.backend.ContainerLogs(ctx, containerName, logsConfig, chStarted); err != nil {
  93. select {
  94. case <-chStarted:
  95. // The client may be expecting all of the data we're sending to
  96. // be multiplexed, so send it through OutStream, which will
  97. // have been set up to handle that if needed.
  98. fmt.Fprintf(logsConfig.OutStream, "Error running logs job: %v\n", err)
  99. default:
  100. return err
  101. }
  102. }
  103. return nil
  104. }
  105. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  106. return s.backend.ContainerExport(vars["name"], w)
  107. }
  108. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  109. // If contentLength is -1, we can assumed chunked encoding
  110. // or more technically that the length is unknown
  111. // https://golang.org/src/pkg/net/http/request.go#L139
  112. // net/http otherwise seems to swallow any headers related to chunked encoding
  113. // including r.TransferEncoding
  114. // allow a nil body for backwards compatibility
  115. version := httputils.VersionFromContext(ctx)
  116. var hostConfig *container.HostConfig
  117. // A non-nil json object is at least 7 characters.
  118. if r.ContentLength > 7 || r.ContentLength == -1 {
  119. if versions.GreaterThanOrEqualTo(version, "1.24") {
  120. return validationError{fmt.Errorf("starting container with non-empty request body was deprecated since v1.10 and removed in v1.12")}
  121. }
  122. if err := httputils.CheckForJSON(r); err != nil {
  123. return err
  124. }
  125. c, err := s.decoder.DecodeHostConfig(r.Body)
  126. if err != nil {
  127. return err
  128. }
  129. hostConfig = c
  130. }
  131. if err := httputils.ParseForm(r); err != nil {
  132. return err
  133. }
  134. checkpoint := r.Form.Get("checkpoint")
  135. checkpointDir := r.Form.Get("checkpoint-dir")
  136. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  137. if err := s.backend.ContainerStart(vars["name"], hostConfig, validateHostname, 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. type errContainerIsRunning interface {
  162. ContainerIsRunning() bool
  163. }
  164. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  165. if err := httputils.ParseForm(r); err != nil {
  166. return err
  167. }
  168. var sig syscall.Signal
  169. name := vars["name"]
  170. // If we have a signal, look at it. Otherwise, do nothing
  171. if sigStr := r.Form.Get("signal"); sigStr != "" {
  172. var err error
  173. if sig, err = signal.ParseSignal(sigStr); err != nil {
  174. return err
  175. }
  176. }
  177. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  178. var isStopped bool
  179. if e, ok := err.(errContainerIsRunning); ok {
  180. isStopped = !e.ContainerIsRunning()
  181. }
  182. // Return error that's not caused because the container is stopped.
  183. // Return error if the container is not running and the api is >= 1.20
  184. // to keep backwards compatibility.
  185. version := httputils.VersionFromContext(ctx)
  186. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  187. return fmt.Errorf("Cannot kill container %s: %v", name, err)
  188. }
  189. }
  190. w.WriteHeader(http.StatusNoContent)
  191. return nil
  192. }
  193. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  194. if err := httputils.ParseForm(r); err != nil {
  195. return err
  196. }
  197. var seconds *int
  198. if tmpSeconds := r.Form.Get("t"); tmpSeconds != "" {
  199. valSeconds, err := strconv.Atoi(tmpSeconds)
  200. if err != nil {
  201. return err
  202. }
  203. seconds = &valSeconds
  204. }
  205. if err := s.backend.ContainerRestart(vars["name"], seconds); err != nil {
  206. return err
  207. }
  208. w.WriteHeader(http.StatusNoContent)
  209. return nil
  210. }
  211. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  212. if err := httputils.ParseForm(r); err != nil {
  213. return err
  214. }
  215. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  216. return err
  217. }
  218. w.WriteHeader(http.StatusNoContent)
  219. return nil
  220. }
  221. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  222. if err := httputils.ParseForm(r); err != nil {
  223. return err
  224. }
  225. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  226. return err
  227. }
  228. w.WriteHeader(http.StatusNoContent)
  229. return nil
  230. }
  231. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  232. status, err := s.backend.ContainerWait(vars["name"], -1*time.Second)
  233. if err != nil {
  234. return err
  235. }
  236. return httputils.WriteJSON(w, http.StatusOK, &container.ContainerWaitOKBody{
  237. StatusCode: int64(status),
  238. })
  239. }
  240. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  241. changes, err := s.backend.ContainerChanges(vars["name"])
  242. if err != nil {
  243. return err
  244. }
  245. return httputils.WriteJSON(w, http.StatusOK, changes)
  246. }
  247. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  248. if err := httputils.ParseForm(r); err != nil {
  249. return err
  250. }
  251. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  252. if err != nil {
  253. return err
  254. }
  255. return httputils.WriteJSON(w, http.StatusOK, procList)
  256. }
  257. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  258. if err := httputils.ParseForm(r); err != nil {
  259. return err
  260. }
  261. name := vars["name"]
  262. newName := r.Form.Get("name")
  263. if err := s.backend.ContainerRename(name, newName); err != nil {
  264. return err
  265. }
  266. w.WriteHeader(http.StatusNoContent)
  267. return nil
  268. }
  269. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  270. if err := httputils.ParseForm(r); err != nil {
  271. return err
  272. }
  273. if err := httputils.CheckForJSON(r); err != nil {
  274. return err
  275. }
  276. version := httputils.VersionFromContext(ctx)
  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. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  288. resp, err := s.backend.ContainerUpdate(name, hostConfig, validateHostname)
  289. if err != nil {
  290. return err
  291. }
  292. return httputils.WriteJSON(w, http.StatusOK, resp)
  293. }
  294. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  295. if err := httputils.ParseForm(r); err != nil {
  296. return err
  297. }
  298. if err := httputils.CheckForJSON(r); err != nil {
  299. return err
  300. }
  301. name := r.Form.Get("name")
  302. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  303. if err != nil {
  304. return err
  305. }
  306. version := httputils.VersionFromContext(ctx)
  307. adjustCPUShares := versions.LessThan(version, "1.19")
  308. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  309. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  310. Name: name,
  311. Config: config,
  312. HostConfig: hostConfig,
  313. NetworkingConfig: networkingConfig,
  314. AdjustCPUShares: adjustCPUShares,
  315. }, validateHostname)
  316. if err != nil {
  317. return err
  318. }
  319. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  320. }
  321. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  322. if err := httputils.ParseForm(r); err != nil {
  323. return err
  324. }
  325. name := vars["name"]
  326. config := &types.ContainerRmConfig{
  327. ForceRemove: httputils.BoolValue(r, "force"),
  328. RemoveVolume: httputils.BoolValue(r, "v"),
  329. RemoveLink: httputils.BoolValue(r, "link"),
  330. }
  331. if err := s.backend.ContainerRm(name, config); err != nil {
  332. return err
  333. }
  334. w.WriteHeader(http.StatusNoContent)
  335. return nil
  336. }
  337. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  338. if err := httputils.ParseForm(r); err != nil {
  339. return err
  340. }
  341. height, err := strconv.Atoi(r.Form.Get("h"))
  342. if err != nil {
  343. return err
  344. }
  345. width, err := strconv.Atoi(r.Form.Get("w"))
  346. if err != nil {
  347. return err
  348. }
  349. return s.backend.ContainerResize(vars["name"], height, width)
  350. }
  351. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  352. err := httputils.ParseForm(r)
  353. if err != nil {
  354. return err
  355. }
  356. containerName := vars["name"]
  357. _, upgrade := r.Header["Upgrade"]
  358. detachKeys := r.FormValue("detachKeys")
  359. hijacker, ok := w.(http.Hijacker)
  360. if !ok {
  361. return fmt.Errorf("error attaching to container %s, hijack connection missing", containerName)
  362. }
  363. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  364. conn, _, err := hijacker.Hijack()
  365. if err != nil {
  366. return nil, nil, nil, err
  367. }
  368. // set raw mode
  369. conn.Write([]byte{})
  370. if upgrade {
  371. 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")
  372. } else {
  373. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  374. }
  375. closer := func() error {
  376. httputils.CloseStreams(conn)
  377. return nil
  378. }
  379. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  380. }
  381. attachConfig := &backend.ContainerAttachConfig{
  382. GetStreams: setupStreams,
  383. UseStdin: httputils.BoolValue(r, "stdin"),
  384. UseStdout: httputils.BoolValue(r, "stdout"),
  385. UseStderr: httputils.BoolValue(r, "stderr"),
  386. Logs: httputils.BoolValue(r, "logs"),
  387. Stream: httputils.BoolValue(r, "stream"),
  388. DetachKeys: detachKeys,
  389. MuxStreams: true,
  390. }
  391. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  392. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  393. // Remember to close stream if error happens
  394. conn, _, errHijack := hijacker.Hijack()
  395. if errHijack == nil {
  396. statusCode := httputils.GetHTTPErrorStatusCode(err)
  397. statusText := http.StatusText(statusCode)
  398. 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())
  399. httputils.CloseStreams(conn)
  400. } else {
  401. logrus.Errorf("Error Hijacking: %v", err)
  402. }
  403. }
  404. return nil
  405. }
  406. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  407. if err := httputils.ParseForm(r); err != nil {
  408. return err
  409. }
  410. containerName := vars["name"]
  411. var err error
  412. detachKeys := r.FormValue("detachKeys")
  413. done := make(chan struct{})
  414. started := make(chan struct{})
  415. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  416. wsChan := make(chan *websocket.Conn)
  417. h := func(conn *websocket.Conn) {
  418. wsChan <- conn
  419. <-done
  420. }
  421. srv := websocket.Server{Handler: h, Handshake: nil}
  422. go func() {
  423. close(started)
  424. srv.ServeHTTP(w, r)
  425. }()
  426. conn := <-wsChan
  427. return conn, conn, conn, nil
  428. }
  429. attachConfig := &backend.ContainerAttachConfig{
  430. GetStreams: setupStreams,
  431. Logs: httputils.BoolValue(r, "logs"),
  432. Stream: httputils.BoolValue(r, "stream"),
  433. DetachKeys: detachKeys,
  434. UseStdin: true,
  435. UseStdout: true,
  436. UseStderr: true,
  437. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  438. }
  439. err = s.backend.ContainerAttach(containerName, attachConfig)
  440. close(done)
  441. select {
  442. case <-started:
  443. logrus.Errorf("Error attaching websocket: %s", err)
  444. return nil
  445. default:
  446. }
  447. return err
  448. }
  449. func (s *containerRouter) postContainersPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  450. if err := httputils.ParseForm(r); err != nil {
  451. return err
  452. }
  453. if err := httputils.CheckForJSON(r); err != nil {
  454. return err
  455. }
  456. var cfg types.ContainersPruneConfig
  457. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  458. return err
  459. }
  460. pruneReport, err := s.backend.ContainersPrune(&cfg)
  461. if err != nil {
  462. return err
  463. }
  464. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  465. }