container_routes.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. package container
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "syscall"
  10. "time"
  11. "github.com/Sirupsen/logrus"
  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. Filter: 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 send it through OutStream, which will
  98. // have been set up to handle that if needed.
  99. fmt.Fprintf(logsConfig.OutStream, "Error running logs job: %v\n", err)
  100. default:
  101. return err
  102. }
  103. }
  104. return nil
  105. }
  106. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  107. return s.backend.ContainerExport(vars["name"], w)
  108. }
  109. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  110. // If contentLength is -1, we can assumed chunked encoding
  111. // or more technically that the length is unknown
  112. // https://golang.org/src/pkg/net/http/request.go#L139
  113. // net/http otherwise seems to swallow any headers related to chunked encoding
  114. // including r.TransferEncoding
  115. // allow a nil body for backwards compatibility
  116. version := httputils.VersionFromContext(ctx)
  117. var hostConfig *container.HostConfig
  118. // A non-nil json object is at least 7 characters.
  119. if r.ContentLength > 7 || r.ContentLength == -1 {
  120. if versions.GreaterThanOrEqualTo(version, "1.24") {
  121. return validationError{fmt.Errorf("starting container with non-empty request body was deprecated since v1.10 and removed in v1.12")}
  122. }
  123. if err := httputils.CheckForJSON(r); err != nil {
  124. return err
  125. }
  126. c, err := s.decoder.DecodeHostConfig(r.Body)
  127. if err != nil {
  128. return err
  129. }
  130. hostConfig = c
  131. }
  132. if err := httputils.ParseForm(r); err != nil {
  133. return err
  134. }
  135. checkpoint := r.Form.Get("checkpoint")
  136. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  137. if err := s.backend.ContainerStart(vars["name"], hostConfig, validateHostname, checkpoint); 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. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  148. if err := s.backend.ContainerStop(vars["name"], seconds); err != nil {
  149. return err
  150. }
  151. w.WriteHeader(http.StatusNoContent)
  152. return nil
  153. }
  154. type errContainerIsRunning interface {
  155. ContainerIsRunning() bool
  156. }
  157. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  158. if err := httputils.ParseForm(r); err != nil {
  159. return err
  160. }
  161. var sig syscall.Signal
  162. name := vars["name"]
  163. // If we have a signal, look at it. Otherwise, do nothing
  164. if sigStr := r.Form.Get("signal"); sigStr != "" {
  165. var err error
  166. if sig, err = signal.ParseSignal(sigStr); err != nil {
  167. return err
  168. }
  169. }
  170. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  171. var isStopped bool
  172. if e, ok := err.(errContainerIsRunning); ok {
  173. isStopped = !e.ContainerIsRunning()
  174. }
  175. // Return error that's not caused because the container is stopped.
  176. // Return error if the container is not running and the api is >= 1.20
  177. // to keep backwards compatibility.
  178. version := httputils.VersionFromContext(ctx)
  179. if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
  180. return fmt.Errorf("Cannot kill container %s: %v", name, err)
  181. }
  182. }
  183. w.WriteHeader(http.StatusNoContent)
  184. return nil
  185. }
  186. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  187. if err := httputils.ParseForm(r); err != nil {
  188. return err
  189. }
  190. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  191. if err := s.backend.ContainerRestart(vars["name"], timeout); err != nil {
  192. return err
  193. }
  194. w.WriteHeader(http.StatusNoContent)
  195. return nil
  196. }
  197. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  198. if err := httputils.ParseForm(r); err != nil {
  199. return err
  200. }
  201. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  202. return err
  203. }
  204. w.WriteHeader(http.StatusNoContent)
  205. return nil
  206. }
  207. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  208. if err := httputils.ParseForm(r); err != nil {
  209. return err
  210. }
  211. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  212. return err
  213. }
  214. w.WriteHeader(http.StatusNoContent)
  215. return nil
  216. }
  217. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  218. status, err := s.backend.ContainerWait(vars["name"], -1*time.Second)
  219. if err != nil {
  220. return err
  221. }
  222. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  223. StatusCode: status,
  224. })
  225. }
  226. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  227. changes, err := s.backend.ContainerChanges(vars["name"])
  228. if err != nil {
  229. return err
  230. }
  231. return httputils.WriteJSON(w, http.StatusOK, changes)
  232. }
  233. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  234. if err := httputils.ParseForm(r); err != nil {
  235. return err
  236. }
  237. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  238. if err != nil {
  239. return err
  240. }
  241. return httputils.WriteJSON(w, http.StatusOK, procList)
  242. }
  243. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  244. if err := httputils.ParseForm(r); err != nil {
  245. return err
  246. }
  247. name := vars["name"]
  248. newName := r.Form.Get("name")
  249. if err := s.backend.ContainerRename(name, newName); err != nil {
  250. return err
  251. }
  252. w.WriteHeader(http.StatusNoContent)
  253. return nil
  254. }
  255. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  256. if err := httputils.ParseForm(r); err != nil {
  257. return err
  258. }
  259. if err := httputils.CheckForJSON(r); err != nil {
  260. return err
  261. }
  262. version := httputils.VersionFromContext(ctx)
  263. var updateConfig container.UpdateConfig
  264. decoder := json.NewDecoder(r.Body)
  265. if err := decoder.Decode(&updateConfig); err != nil {
  266. return err
  267. }
  268. hostConfig := &container.HostConfig{
  269. Resources: updateConfig.Resources,
  270. RestartPolicy: updateConfig.RestartPolicy,
  271. }
  272. name := vars["name"]
  273. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  274. resp, err := s.backend.ContainerUpdate(name, hostConfig, validateHostname)
  275. if err != nil {
  276. return err
  277. }
  278. return httputils.WriteJSON(w, http.StatusOK, resp)
  279. }
  280. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  281. if err := httputils.ParseForm(r); err != nil {
  282. return err
  283. }
  284. if err := httputils.CheckForJSON(r); err != nil {
  285. return err
  286. }
  287. name := r.Form.Get("name")
  288. config, hostConfig, networkingConfig, err := s.decoder.DecodeConfig(r.Body)
  289. if err != nil {
  290. return err
  291. }
  292. version := httputils.VersionFromContext(ctx)
  293. adjustCPUShares := versions.LessThan(version, "1.19")
  294. validateHostname := versions.GreaterThanOrEqualTo(version, "1.24")
  295. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  296. Name: name,
  297. Config: config,
  298. HostConfig: hostConfig,
  299. NetworkingConfig: networkingConfig,
  300. AdjustCPUShares: adjustCPUShares,
  301. }, validateHostname)
  302. if err != nil {
  303. return err
  304. }
  305. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  306. }
  307. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  308. if err := httputils.ParseForm(r); err != nil {
  309. return err
  310. }
  311. name := vars["name"]
  312. config := &types.ContainerRmConfig{
  313. ForceRemove: httputils.BoolValue(r, "force"),
  314. RemoveVolume: httputils.BoolValue(r, "v"),
  315. RemoveLink: httputils.BoolValue(r, "link"),
  316. }
  317. if err := s.backend.ContainerRm(name, config); err != nil {
  318. // Force a 404 for the empty string
  319. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  320. return fmt.Errorf("no such container: \"\"")
  321. }
  322. return err
  323. }
  324. w.WriteHeader(http.StatusNoContent)
  325. return nil
  326. }
  327. func (s *containerRouter) postContainersResize(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. height, err := strconv.Atoi(r.Form.Get("h"))
  332. if err != nil {
  333. return err
  334. }
  335. width, err := strconv.Atoi(r.Form.Get("w"))
  336. if err != nil {
  337. return err
  338. }
  339. return s.backend.ContainerResize(vars["name"], height, width)
  340. }
  341. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  342. err := httputils.ParseForm(r)
  343. if err != nil {
  344. return err
  345. }
  346. containerName := vars["name"]
  347. _, upgrade := r.Header["Upgrade"]
  348. detachKeys := r.FormValue("detachKeys")
  349. hijacker, ok := w.(http.Hijacker)
  350. if !ok {
  351. return fmt.Errorf("error attaching to container %s, hijack connection missing", containerName)
  352. }
  353. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  354. conn, _, err := hijacker.Hijack()
  355. if err != nil {
  356. return nil, nil, nil, err
  357. }
  358. // set raw mode
  359. conn.Write([]byte{})
  360. if upgrade {
  361. 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")
  362. } else {
  363. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  364. }
  365. closer := func() error {
  366. httputils.CloseStreams(conn)
  367. return nil
  368. }
  369. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  370. }
  371. attachConfig := &backend.ContainerAttachConfig{
  372. GetStreams: setupStreams,
  373. UseStdin: httputils.BoolValue(r, "stdin"),
  374. UseStdout: httputils.BoolValue(r, "stdout"),
  375. UseStderr: httputils.BoolValue(r, "stderr"),
  376. Logs: httputils.BoolValue(r, "logs"),
  377. Stream: httputils.BoolValue(r, "stream"),
  378. DetachKeys: detachKeys,
  379. MuxStreams: true,
  380. }
  381. if err = s.backend.ContainerAttach(containerName, attachConfig); err != nil {
  382. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  383. // Remember to close stream if error happens
  384. conn, _, errHijack := hijacker.Hijack()
  385. if errHijack == nil {
  386. statusCode := httputils.GetHTTPErrorStatusCode(err)
  387. statusText := http.StatusText(statusCode)
  388. 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())
  389. httputils.CloseStreams(conn)
  390. } else {
  391. logrus.Errorf("Error Hijacking: %v", err)
  392. }
  393. }
  394. return nil
  395. }
  396. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  397. if err := httputils.ParseForm(r); err != nil {
  398. return err
  399. }
  400. containerName := vars["name"]
  401. var err error
  402. detachKeys := r.FormValue("detachKeys")
  403. done := make(chan struct{})
  404. started := make(chan struct{})
  405. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  406. wsChan := make(chan *websocket.Conn)
  407. h := func(conn *websocket.Conn) {
  408. wsChan <- conn
  409. <-done
  410. }
  411. srv := websocket.Server{Handler: h, Handshake: nil}
  412. go func() {
  413. close(started)
  414. srv.ServeHTTP(w, r)
  415. }()
  416. conn := <-wsChan
  417. return conn, conn, conn, nil
  418. }
  419. attachConfig := &backend.ContainerAttachConfig{
  420. GetStreams: setupStreams,
  421. Logs: httputils.BoolValue(r, "logs"),
  422. Stream: httputils.BoolValue(r, "stream"),
  423. DetachKeys: detachKeys,
  424. UseStdin: true,
  425. UseStdout: true,
  426. UseStderr: true,
  427. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  428. }
  429. err = s.backend.ContainerAttach(containerName, attachConfig)
  430. close(done)
  431. select {
  432. case <-started:
  433. logrus.Errorf("Error attaching websocket: %s", err)
  434. return nil
  435. default:
  436. }
  437. return err
  438. }