container_routes.go 15 KB

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