container_routes.go 14 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/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. var closeNotifier <-chan bool
  61. if notifier, ok := w.(http.CloseNotifier); ok {
  62. closeNotifier = notifier.CloseNotify()
  63. }
  64. config := &backend.ContainerStatsConfig{
  65. Stream: stream,
  66. OutStream: w,
  67. Stop: closeNotifier,
  68. Version: string(httputils.VersionFromContext(ctx)),
  69. }
  70. return s.backend.ContainerStats(vars["name"], config)
  71. }
  72. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  73. if err := httputils.ParseForm(r); err != nil {
  74. return err
  75. }
  76. // Args are validated before the stream starts because when it starts we're
  77. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  78. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  79. // any error after the stream starts (i.e. container not found, wrong parameters)
  80. // with the appropriate status code.
  81. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  82. if !(stdout || stderr) {
  83. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  84. }
  85. var closeNotifier <-chan bool
  86. if notifier, ok := w.(http.CloseNotifier); ok {
  87. closeNotifier = notifier.CloseNotify()
  88. }
  89. containerName := vars["name"]
  90. logsConfig := &backend.ContainerLogsConfig{
  91. ContainerLogsOptions: types.ContainerLogsOptions{
  92. Follow: httputils.BoolValue(r, "follow"),
  93. Timestamps: httputils.BoolValue(r, "timestamps"),
  94. Since: r.Form.Get("since"),
  95. Tail: r.Form.Get("tail"),
  96. ShowStdout: stdout,
  97. ShowStderr: stderr,
  98. },
  99. OutStream: w,
  100. Stop: closeNotifier,
  101. }
  102. chStarted := make(chan struct{})
  103. if err := s.backend.ContainerLogs(containerName, logsConfig, chStarted); err != nil {
  104. select {
  105. case <-chStarted:
  106. // The client may be expecting all of the data we're sending to
  107. // be multiplexed, so send it through OutStream, which will
  108. // have been set up to handle that if needed.
  109. fmt.Fprintf(logsConfig.OutStream, "Error running logs job: %v\n", err)
  110. default:
  111. return err
  112. }
  113. }
  114. return nil
  115. }
  116. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  117. return s.backend.ContainerExport(vars["name"], w)
  118. }
  119. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  120. // If contentLength is -1, we can assumed chunked encoding
  121. // or more technically that the length is unknown
  122. // https://golang.org/src/pkg/net/http/request.go#L139
  123. // net/http otherwise seems to swallow any headers related to chunked encoding
  124. // including r.TransferEncoding
  125. // allow a nil body for backwards compatibility
  126. var hostConfig *container.HostConfig
  127. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  128. if err := httputils.CheckForJSON(r); err != nil {
  129. return err
  130. }
  131. c, err := runconfig.DecodeHostConfig(r.Body)
  132. if err != nil {
  133. return err
  134. }
  135. hostConfig = c
  136. }
  137. if err := s.backend.ContainerStart(vars["name"], hostConfig); 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 version.GreaterThanOrEqualTo("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. var updateConfig container.UpdateConfig
  263. decoder := json.NewDecoder(r.Body)
  264. if err := decoder.Decode(&updateConfig); err != nil {
  265. return err
  266. }
  267. hostConfig := &container.HostConfig{
  268. Resources: updateConfig.Resources,
  269. RestartPolicy: updateConfig.RestartPolicy,
  270. }
  271. name := vars["name"]
  272. warnings, err := s.backend.ContainerUpdate(name, hostConfig)
  273. if err != nil {
  274. return err
  275. }
  276. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerUpdateResponse{
  277. Warnings: warnings,
  278. })
  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 := runconfig.DecodeContainerConfig(r.Body)
  289. if err != nil {
  290. return err
  291. }
  292. version := httputils.VersionFromContext(ctx)
  293. adjustCPUShares := version.LessThan("1.19")
  294. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  295. Name: name,
  296. Config: config,
  297. HostConfig: hostConfig,
  298. NetworkingConfig: networkingConfig,
  299. AdjustCPUShares: adjustCPUShares,
  300. })
  301. if err != nil {
  302. return err
  303. }
  304. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  305. }
  306. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  307. if err := httputils.ParseForm(r); err != nil {
  308. return err
  309. }
  310. name := vars["name"]
  311. config := &types.ContainerRmConfig{
  312. ForceRemove: httputils.BoolValue(r, "force"),
  313. RemoveVolume: httputils.BoolValue(r, "v"),
  314. RemoveLink: httputils.BoolValue(r, "link"),
  315. }
  316. if err := s.backend.ContainerRm(name, config); err != nil {
  317. // Force a 404 for the empty string
  318. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  319. return fmt.Errorf("no such container: \"\"")
  320. }
  321. return err
  322. }
  323. w.WriteHeader(http.StatusNoContent)
  324. return nil
  325. }
  326. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  327. if err := httputils.ParseForm(r); err != nil {
  328. return err
  329. }
  330. height, err := strconv.Atoi(r.Form.Get("h"))
  331. if err != nil {
  332. return err
  333. }
  334. width, err := strconv.Atoi(r.Form.Get("w"))
  335. if err != nil {
  336. return err
  337. }
  338. return s.backend.ContainerResize(vars["name"], height, width)
  339. }
  340. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  341. err := httputils.ParseForm(r)
  342. if err != nil {
  343. return err
  344. }
  345. containerName := vars["name"]
  346. _, upgrade := r.Header["Upgrade"]
  347. keys := []byte{}
  348. detachKeys := r.FormValue("detachKeys")
  349. if detachKeys != "" {
  350. keys, err = term.ToBytes(detachKeys)
  351. if err != nil {
  352. logrus.Warnf("Invalid escape keys provided (%s) using default : ctrl-p ctrl-q", detachKeys)
  353. }
  354. }
  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: keys,
  385. MuxStreams: true,
  386. }
  387. return s.backend.ContainerAttach(containerName, attachConfig)
  388. }
  389. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  390. if err := httputils.ParseForm(r); err != nil {
  391. return err
  392. }
  393. containerName := vars["name"]
  394. var keys []byte
  395. var err error
  396. detachKeys := r.FormValue("detachKeys")
  397. if detachKeys != "" {
  398. keys, err = term.ToBytes(detachKeys)
  399. if err != nil {
  400. logrus.Warnf("Invalid escape keys provided (%s) using default : ctrl-p ctrl-q", detachKeys)
  401. }
  402. }
  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: keys,
  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. }