container_routes.go 14 KB

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