container_routes.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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/docker/pkg/term"
  17. "github.com/docker/docker/runconfig"
  18. "github.com/docker/engine-api/types"
  19. "github.com/docker/engine-api/types/container"
  20. "github.com/docker/engine-api/types/filters"
  21. "golang.org/x/net/context"
  22. "golang.org/x/net/websocket"
  23. )
  24. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  25. if err := httputils.ParseForm(r); err != nil {
  26. return err
  27. }
  28. filter, err := filters.FromParam(r.Form.Get("filters"))
  29. if err != nil {
  30. return err
  31. }
  32. config := &types.ContainerListOptions{
  33. All: httputils.BoolValue(r, "all"),
  34. Size: httputils.BoolValue(r, "size"),
  35. Since: r.Form.Get("since"),
  36. Before: r.Form.Get("before"),
  37. Filter: filter,
  38. }
  39. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  40. limit, err := strconv.Atoi(tmpLimit)
  41. if err != nil {
  42. return err
  43. }
  44. config.Limit = limit
  45. }
  46. containers, err := s.backend.Containers(config)
  47. if err != nil {
  48. return err
  49. }
  50. return httputils.WriteJSON(w, http.StatusOK, containers)
  51. }
  52. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  53. if err := httputils.ParseForm(r); err != nil {
  54. return err
  55. }
  56. stream := httputils.BoolValueOrDefault(r, "stream", true)
  57. if !stream {
  58. w.Header().Set("Content-Type", "application/json")
  59. }
  60. config := &backend.ContainerStatsConfig{
  61. Stream: stream,
  62. OutStream: w,
  63. Version: string(httputils.VersionFromContext(ctx)),
  64. }
  65. return s.backend.ContainerStats(ctx, vars["name"], config)
  66. }
  67. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  68. if err := httputils.ParseForm(r); err != nil {
  69. return err
  70. }
  71. // Args are validated before the stream starts because when it starts we're
  72. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  73. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  74. // any error after the stream starts (i.e. container not found, wrong parameters)
  75. // with the appropriate status code.
  76. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  77. if !(stdout || stderr) {
  78. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  79. }
  80. containerName := vars["name"]
  81. logsConfig := &backend.ContainerLogsConfig{
  82. ContainerLogsOptions: types.ContainerLogsOptions{
  83. Follow: httputils.BoolValue(r, "follow"),
  84. Timestamps: httputils.BoolValue(r, "timestamps"),
  85. Since: r.Form.Get("since"),
  86. Tail: r.Form.Get("tail"),
  87. ShowStdout: stdout,
  88. ShowStderr: stderr,
  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. var hostConfig *container.HostConfig
  117. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  118. if err := httputils.CheckForJSON(r); err != nil {
  119. return err
  120. }
  121. c, err := runconfig.DecodeHostConfig(r.Body)
  122. if err != nil {
  123. return err
  124. }
  125. hostConfig = c
  126. }
  127. if err := s.backend.ContainerStart(vars["name"], hostConfig); err != nil {
  128. return err
  129. }
  130. w.WriteHeader(http.StatusNoContent)
  131. return nil
  132. }
  133. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  134. if err := httputils.ParseForm(r); err != nil {
  135. return err
  136. }
  137. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  138. if err := s.backend.ContainerStop(vars["name"], seconds); err != nil {
  139. return err
  140. }
  141. w.WriteHeader(http.StatusNoContent)
  142. return nil
  143. }
  144. type errContainerIsRunning interface {
  145. ContainerIsRunning() bool
  146. }
  147. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  148. if err := httputils.ParseForm(r); err != nil {
  149. return err
  150. }
  151. var sig syscall.Signal
  152. name := vars["name"]
  153. // If we have a signal, look at it. Otherwise, do nothing
  154. if sigStr := r.Form.Get("signal"); sigStr != "" {
  155. var err error
  156. if sig, err = signal.ParseSignal(sigStr); err != nil {
  157. return err
  158. }
  159. }
  160. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  161. var isStopped bool
  162. if e, ok := err.(errContainerIsRunning); ok {
  163. isStopped = !e.ContainerIsRunning()
  164. }
  165. // Return error that's not caused because the container is stopped.
  166. // Return error if the container is not running and the api is >= 1.20
  167. // to keep backwards compatibility.
  168. version := httputils.VersionFromContext(ctx)
  169. if version.GreaterThanOrEqualTo("1.20") || !isStopped {
  170. return fmt.Errorf("Cannot kill container %s: %v", name, err)
  171. }
  172. }
  173. w.WriteHeader(http.StatusNoContent)
  174. return nil
  175. }
  176. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  177. if err := httputils.ParseForm(r); err != nil {
  178. return err
  179. }
  180. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  181. if err := s.backend.ContainerRestart(vars["name"], timeout); err != nil {
  182. return err
  183. }
  184. w.WriteHeader(http.StatusNoContent)
  185. return nil
  186. }
  187. func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  188. if err := httputils.ParseForm(r); err != nil {
  189. return err
  190. }
  191. if err := s.backend.ContainerPause(vars["name"]); err != nil {
  192. return err
  193. }
  194. w.WriteHeader(http.StatusNoContent)
  195. return nil
  196. }
  197. func (s *containerRouter) postContainersUnpause(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.ContainerUnpause(vars["name"]); err != nil {
  202. return err
  203. }
  204. w.WriteHeader(http.StatusNoContent)
  205. return nil
  206. }
  207. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  208. status, err := s.backend.ContainerWait(vars["name"], -1*time.Second)
  209. if err != nil {
  210. return err
  211. }
  212. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  213. StatusCode: status,
  214. })
  215. }
  216. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  217. changes, err := s.backend.ContainerChanges(vars["name"])
  218. if err != nil {
  219. return err
  220. }
  221. return httputils.WriteJSON(w, http.StatusOK, changes)
  222. }
  223. func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  224. if err := httputils.ParseForm(r); err != nil {
  225. return err
  226. }
  227. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  228. if err != nil {
  229. return err
  230. }
  231. return httputils.WriteJSON(w, http.StatusOK, procList)
  232. }
  233. func (s *containerRouter) postContainerRename(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. name := vars["name"]
  238. newName := r.Form.Get("name")
  239. if err := s.backend.ContainerRename(name, newName); err != nil {
  240. return err
  241. }
  242. w.WriteHeader(http.StatusNoContent)
  243. return nil
  244. }
  245. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  246. if err := httputils.ParseForm(r); err != nil {
  247. return err
  248. }
  249. if err := httputils.CheckForJSON(r); err != nil {
  250. return err
  251. }
  252. var updateConfig container.UpdateConfig
  253. decoder := json.NewDecoder(r.Body)
  254. if err := decoder.Decode(&updateConfig); err != nil {
  255. return err
  256. }
  257. hostConfig := &container.HostConfig{
  258. Resources: updateConfig.Resources,
  259. RestartPolicy: updateConfig.RestartPolicy,
  260. }
  261. name := vars["name"]
  262. warnings, err := s.backend.ContainerUpdate(name, hostConfig)
  263. if err != nil {
  264. return err
  265. }
  266. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerUpdateResponse{
  267. Warnings: warnings,
  268. })
  269. }
  270. func (s *containerRouter) postContainersCreate(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. name := r.Form.Get("name")
  278. config, hostConfig, networkingConfig, err := runconfig.DecodeContainerConfig(r.Body)
  279. if err != nil {
  280. return err
  281. }
  282. version := httputils.VersionFromContext(ctx)
  283. adjustCPUShares := version.LessThan("1.19")
  284. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  285. Name: name,
  286. Config: config,
  287. HostConfig: hostConfig,
  288. NetworkingConfig: networkingConfig,
  289. AdjustCPUShares: adjustCPUShares,
  290. })
  291. if err != nil {
  292. return err
  293. }
  294. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  295. }
  296. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  297. if err := httputils.ParseForm(r); err != nil {
  298. return err
  299. }
  300. name := vars["name"]
  301. config := &types.ContainerRmConfig{
  302. ForceRemove: httputils.BoolValue(r, "force"),
  303. RemoveVolume: httputils.BoolValue(r, "v"),
  304. RemoveLink: httputils.BoolValue(r, "link"),
  305. }
  306. if err := s.backend.ContainerRm(name, config); err != nil {
  307. // Force a 404 for the empty string
  308. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  309. return fmt.Errorf("no such container: \"\"")
  310. }
  311. return err
  312. }
  313. w.WriteHeader(http.StatusNoContent)
  314. return nil
  315. }
  316. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  317. if err := httputils.ParseForm(r); err != nil {
  318. return err
  319. }
  320. height, err := strconv.Atoi(r.Form.Get("h"))
  321. if err != nil {
  322. return err
  323. }
  324. width, err := strconv.Atoi(r.Form.Get("w"))
  325. if err != nil {
  326. return err
  327. }
  328. return s.backend.ContainerResize(vars["name"], height, width)
  329. }
  330. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  331. err := httputils.ParseForm(r)
  332. if err != nil {
  333. return err
  334. }
  335. containerName := vars["name"]
  336. _, upgrade := r.Header["Upgrade"]
  337. keys := []byte{}
  338. detachKeys := r.FormValue("detachKeys")
  339. if detachKeys != "" {
  340. keys, err = term.ToBytes(detachKeys)
  341. if err != nil {
  342. logrus.Warnf("Invalid escape keys provided (%s) using default : ctrl-p ctrl-q", detachKeys)
  343. }
  344. }
  345. hijacker, ok := w.(http.Hijacker)
  346. if !ok {
  347. return fmt.Errorf("error attaching to container %s, hijack connection missing", containerName)
  348. }
  349. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  350. conn, _, err := hijacker.Hijack()
  351. if err != nil {
  352. return nil, nil, nil, err
  353. }
  354. // set raw mode
  355. conn.Write([]byte{})
  356. if upgrade {
  357. 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")
  358. } else {
  359. fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  360. }
  361. closer := func() error {
  362. httputils.CloseStreams(conn)
  363. return nil
  364. }
  365. return ioutils.NewReadCloserWrapper(conn, closer), conn, conn, nil
  366. }
  367. attachConfig := &backend.ContainerAttachConfig{
  368. GetStreams: setupStreams,
  369. UseStdin: httputils.BoolValue(r, "stdin"),
  370. UseStdout: httputils.BoolValue(r, "stdout"),
  371. UseStderr: httputils.BoolValue(r, "stderr"),
  372. Logs: httputils.BoolValue(r, "logs"),
  373. Stream: httputils.BoolValue(r, "stream"),
  374. DetachKeys: keys,
  375. MuxStreams: true,
  376. }
  377. return s.backend.ContainerAttach(containerName, attachConfig)
  378. }
  379. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  380. if err := httputils.ParseForm(r); err != nil {
  381. return err
  382. }
  383. containerName := vars["name"]
  384. var keys []byte
  385. var err error
  386. detachKeys := r.FormValue("detachKeys")
  387. if detachKeys != "" {
  388. keys, err = term.ToBytes(detachKeys)
  389. if err != nil {
  390. logrus.Warnf("Invalid escape keys provided (%s) using default : ctrl-p ctrl-q", detachKeys)
  391. }
  392. }
  393. done := make(chan struct{})
  394. started := make(chan struct{})
  395. setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) {
  396. wsChan := make(chan *websocket.Conn)
  397. h := func(conn *websocket.Conn) {
  398. wsChan <- conn
  399. <-done
  400. }
  401. srv := websocket.Server{Handler: h, Handshake: nil}
  402. go func() {
  403. close(started)
  404. srv.ServeHTTP(w, r)
  405. }()
  406. conn := <-wsChan
  407. return conn, conn, conn, nil
  408. }
  409. attachConfig := &backend.ContainerAttachConfig{
  410. GetStreams: setupStreams,
  411. Logs: httputils.BoolValue(r, "logs"),
  412. Stream: httputils.BoolValue(r, "stream"),
  413. DetachKeys: keys,
  414. UseStdin: true,
  415. UseStdout: true,
  416. UseStderr: true,
  417. MuxStreams: false, // TODO: this should be true since it's a single stream for both stdout and stderr
  418. }
  419. err = s.backend.ContainerAttach(containerName, attachConfig)
  420. close(done)
  421. select {
  422. case <-started:
  423. logrus.Errorf("Error attaching websocket: %s", err)
  424. return nil
  425. default:
  426. }
  427. return err
  428. }