container_routes.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "syscall"
  9. "time"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/distribution/registry/api/errcode"
  12. "github.com/docker/docker/api/server/httputils"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/api/types/container"
  15. timetypes "github.com/docker/docker/api/types/time"
  16. "github.com/docker/docker/daemon"
  17. derr "github.com/docker/docker/errors"
  18. "github.com/docker/docker/pkg/ioutils"
  19. "github.com/docker/docker/pkg/signal"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/docker/utils"
  22. "golang.org/x/net/context"
  23. "golang.org/x/net/websocket"
  24. )
  25. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  26. if err := httputils.ParseForm(r); err != nil {
  27. return err
  28. }
  29. config := &daemon.ContainersConfig{
  30. All: httputils.BoolValue(r, "all"),
  31. Size: httputils.BoolValue(r, "size"),
  32. Since: r.Form.Get("since"),
  33. Before: r.Form.Get("before"),
  34. Filters: r.Form.Get("filters"),
  35. }
  36. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  37. limit, err := strconv.Atoi(tmpLimit)
  38. if err != nil {
  39. return err
  40. }
  41. config.Limit = limit
  42. }
  43. containers, err := s.backend.Containers(config)
  44. if err != nil {
  45. return err
  46. }
  47. return httputils.WriteJSON(w, http.StatusOK, containers)
  48. }
  49. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  50. if err := httputils.ParseForm(r); err != nil {
  51. return err
  52. }
  53. stream := httputils.BoolValueOrDefault(r, "stream", true)
  54. var out io.Writer
  55. if !stream {
  56. w.Header().Set("Content-Type", "application/json")
  57. out = w
  58. } else {
  59. wf := ioutils.NewWriteFlusher(w)
  60. out = wf
  61. defer wf.Close()
  62. }
  63. var closeNotifier <-chan bool
  64. if notifier, ok := w.(http.CloseNotifier); ok {
  65. closeNotifier = notifier.CloseNotify()
  66. }
  67. config := &daemon.ContainerStatsConfig{
  68. Stream: stream,
  69. OutStream: out,
  70. Stop: closeNotifier,
  71. Version: httputils.VersionFromContext(ctx),
  72. }
  73. return s.backend.ContainerStats(vars["name"], config)
  74. }
  75. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  76. if err := httputils.ParseForm(r); err != nil {
  77. return err
  78. }
  79. // Args are validated before the stream starts because when it starts we're
  80. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  81. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  82. // any error after the stream starts (i.e. container not found, wrong parameters)
  83. // with the appropriate status code.
  84. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  85. if !(stdout || stderr) {
  86. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  87. }
  88. var since time.Time
  89. if r.Form.Get("since") != "" {
  90. s, n, err := timetypes.ParseTimestamps(r.Form.Get("since"), 0)
  91. if err != nil {
  92. return err
  93. }
  94. since = time.Unix(s, n)
  95. }
  96. var closeNotifier <-chan bool
  97. if notifier, ok := w.(http.CloseNotifier); ok {
  98. closeNotifier = notifier.CloseNotify()
  99. }
  100. containerName := vars["name"]
  101. if !s.backend.Exists(containerName) {
  102. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  103. }
  104. // write an empty chunk of data (this is to ensure that the
  105. // HTTP Response is sent immediately, even if the container has
  106. // not yet produced any data)
  107. w.WriteHeader(http.StatusOK)
  108. if flusher, ok := w.(http.Flusher); ok {
  109. flusher.Flush()
  110. }
  111. output := ioutils.NewWriteFlusher(w)
  112. defer output.Close()
  113. logsConfig := &daemon.ContainerLogsConfig{
  114. Follow: httputils.BoolValue(r, "follow"),
  115. Timestamps: httputils.BoolValue(r, "timestamps"),
  116. Since: since,
  117. Tail: r.Form.Get("tail"),
  118. UseStdout: stdout,
  119. UseStderr: stderr,
  120. OutStream: output,
  121. Stop: closeNotifier,
  122. }
  123. if err := s.backend.ContainerLogs(containerName, logsConfig); err != nil {
  124. // The client may be expecting all of the data we're sending to
  125. // be multiplexed, so send it through OutStream, which will
  126. // have been set up to handle that if needed.
  127. fmt.Fprintf(logsConfig.OutStream, "Error running logs job: %s\n", utils.GetErrorMessage(err))
  128. }
  129. return nil
  130. }
  131. func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  132. return s.backend.ContainerExport(vars["name"], w)
  133. }
  134. func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  135. // If contentLength is -1, we can assumed chunked encoding
  136. // or more technically that the length is unknown
  137. // https://golang.org/src/pkg/net/http/request.go#L139
  138. // net/http otherwise seems to swallow any headers related to chunked encoding
  139. // including r.TransferEncoding
  140. // allow a nil body for backwards compatibility
  141. var hostConfig *container.HostConfig
  142. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  143. if err := httputils.CheckForJSON(r); err != nil {
  144. return err
  145. }
  146. c, err := runconfig.DecodeHostConfig(r.Body)
  147. if err != nil {
  148. return err
  149. }
  150. hostConfig = c
  151. }
  152. if err := s.backend.ContainerStart(vars["name"], hostConfig); err != nil {
  153. return err
  154. }
  155. w.WriteHeader(http.StatusNoContent)
  156. return nil
  157. }
  158. func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  159. if err := httputils.ParseForm(r); err != nil {
  160. return err
  161. }
  162. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  163. if err := s.backend.ContainerStop(vars["name"], seconds); err != nil {
  164. return err
  165. }
  166. w.WriteHeader(http.StatusNoContent)
  167. return nil
  168. }
  169. func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  170. if err := httputils.ParseForm(r); err != nil {
  171. return err
  172. }
  173. var sig syscall.Signal
  174. name := vars["name"]
  175. // If we have a signal, look at it. Otherwise, do nothing
  176. if sigStr := r.Form.Get("signal"); sigStr != "" {
  177. var err error
  178. if sig, err = signal.ParseSignal(sigStr); err != nil {
  179. return err
  180. }
  181. }
  182. if err := s.backend.ContainerKill(name, uint64(sig)); err != nil {
  183. theErr, isDerr := err.(errcode.ErrorCoder)
  184. isStopped := isDerr && theErr.ErrorCode() == derr.ErrorCodeNotRunning
  185. // Return error that's not caused because the container is stopped.
  186. // Return error if the container is not running and the api is >= 1.20
  187. // to keep backwards compatibility.
  188. version := httputils.VersionFromContext(ctx)
  189. if version.GreaterThanOrEqualTo("1.20") || !isStopped {
  190. return fmt.Errorf("Cannot kill container %s: %v", name, utils.GetErrorMessage(err))
  191. }
  192. }
  193. w.WriteHeader(http.StatusNoContent)
  194. return nil
  195. }
  196. func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  197. if err := httputils.ParseForm(r); err != nil {
  198. return err
  199. }
  200. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  201. if err := s.backend.ContainerRestart(vars["name"], timeout); err != nil {
  202. return err
  203. }
  204. w.WriteHeader(http.StatusNoContent)
  205. return nil
  206. }
  207. func (s *containerRouter) postContainersPause(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.ContainerPause(vars["name"]); err != nil {
  212. return err
  213. }
  214. w.WriteHeader(http.StatusNoContent)
  215. return nil
  216. }
  217. func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  218. if err := httputils.ParseForm(r); err != nil {
  219. return err
  220. }
  221. if err := s.backend.ContainerUnpause(vars["name"]); err != nil {
  222. return err
  223. }
  224. w.WriteHeader(http.StatusNoContent)
  225. return nil
  226. }
  227. func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  228. status, err := s.backend.ContainerWait(vars["name"], -1*time.Second)
  229. if err != nil {
  230. return err
  231. }
  232. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  233. StatusCode: status,
  234. })
  235. }
  236. func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  237. changes, err := s.backend.ContainerChanges(vars["name"])
  238. if err != nil {
  239. return err
  240. }
  241. return httputils.WriteJSON(w, http.StatusOK, changes)
  242. }
  243. func (s *containerRouter) getContainersTop(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. procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  248. if err != nil {
  249. return err
  250. }
  251. return httputils.WriteJSON(w, http.StatusOK, procList)
  252. }
  253. func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  254. if err := httputils.ParseForm(r); err != nil {
  255. return err
  256. }
  257. name := vars["name"]
  258. newName := r.Form.Get("name")
  259. if err := s.backend.ContainerRename(name, newName); err != nil {
  260. return err
  261. }
  262. w.WriteHeader(http.StatusNoContent)
  263. return nil
  264. }
  265. func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  266. if err := httputils.ParseForm(r); err != nil {
  267. return err
  268. }
  269. if err := httputils.CheckForJSON(r); err != nil {
  270. return err
  271. }
  272. _, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  273. if err != nil {
  274. return err
  275. }
  276. name := vars["name"]
  277. warnings, err := s.backend.ContainerUpdate(name, hostConfig)
  278. if err != nil {
  279. return err
  280. }
  281. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerUpdateResponse{
  282. Warnings: warnings,
  283. })
  284. }
  285. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  286. if err := httputils.ParseForm(r); err != nil {
  287. return err
  288. }
  289. if err := httputils.CheckForJSON(r); err != nil {
  290. return err
  291. }
  292. name := r.Form.Get("name")
  293. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  294. if err != nil {
  295. return err
  296. }
  297. version := httputils.VersionFromContext(ctx)
  298. adjustCPUShares := version.LessThan("1.19")
  299. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  300. Name: name,
  301. Config: config,
  302. HostConfig: hostConfig,
  303. AdjustCPUShares: adjustCPUShares,
  304. })
  305. if err != nil {
  306. return err
  307. }
  308. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  309. }
  310. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  311. if err := httputils.ParseForm(r); err != nil {
  312. return err
  313. }
  314. name := vars["name"]
  315. config := &types.ContainerRmConfig{
  316. ForceRemove: httputils.BoolValue(r, "force"),
  317. RemoveVolume: httputils.BoolValue(r, "v"),
  318. RemoveLink: httputils.BoolValue(r, "link"),
  319. }
  320. if err := s.backend.ContainerRm(name, config); err != nil {
  321. // Force a 404 for the empty string
  322. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  323. return fmt.Errorf("no such container: \"\"")
  324. }
  325. return err
  326. }
  327. w.WriteHeader(http.StatusNoContent)
  328. return nil
  329. }
  330. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  331. if err := httputils.ParseForm(r); err != nil {
  332. return err
  333. }
  334. height, err := strconv.Atoi(r.Form.Get("h"))
  335. if err != nil {
  336. return err
  337. }
  338. width, err := strconv.Atoi(r.Form.Get("w"))
  339. if err != nil {
  340. return err
  341. }
  342. return s.backend.ContainerResize(vars["name"], height, width)
  343. }
  344. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  345. if err := httputils.ParseForm(r); err != nil {
  346. return err
  347. }
  348. containerName := vars["name"]
  349. _, upgrade := r.Header["Upgrade"]
  350. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  351. Hijacker: w.(http.Hijacker),
  352. Upgrade: upgrade,
  353. UseStdin: httputils.BoolValue(r, "stdin"),
  354. UseStdout: httputils.BoolValue(r, "stdout"),
  355. UseStderr: httputils.BoolValue(r, "stderr"),
  356. Logs: httputils.BoolValue(r, "logs"),
  357. Stream: httputils.BoolValue(r, "stream"),
  358. }
  359. return s.backend.ContainerAttachWithLogs(containerName, attachWithLogsConfig)
  360. }
  361. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  362. if err := httputils.ParseForm(r); err != nil {
  363. return err
  364. }
  365. containerName := vars["name"]
  366. if !s.backend.Exists(containerName) {
  367. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  368. }
  369. h := websocket.Handler(func(ws *websocket.Conn) {
  370. defer ws.Close()
  371. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  372. InStream: ws,
  373. OutStream: ws,
  374. ErrStream: ws,
  375. Logs: httputils.BoolValue(r, "logs"),
  376. Stream: httputils.BoolValue(r, "stream"),
  377. }
  378. if err := s.backend.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil {
  379. logrus.Errorf("Error attaching websocket: %s", utils.GetErrorMessage(err))
  380. }
  381. })
  382. ws := websocket.Server{Handler: h, Handshake: nil}
  383. ws.ServeHTTP(w, r)
  384. return nil
  385. }