container_routes.go 15 KB

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