container_routes.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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/distribution/registry/api/errcode"
  13. "github.com/docker/docker/api/server/httputils"
  14. "github.com/docker/docker/api/types/backend"
  15. derr "github.com/docker/docker/errors"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/docker/docker/pkg/signal"
  18. "github.com/docker/docker/pkg/term"
  19. "github.com/docker/docker/runconfig"
  20. "github.com/docker/docker/utils"
  21. "github.com/docker/engine-api/types"
  22. "github.com/docker/engine-api/types/container"
  23. "github.com/docker/engine-api/types/filters"
  24. "golang.org/x/net/context"
  25. "golang.org/x/net/websocket"
  26. )
  27. func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  28. if err := httputils.ParseForm(r); err != nil {
  29. return err
  30. }
  31. filter, err := filters.FromParam(r.Form.Get("filters"))
  32. if err != nil {
  33. return err
  34. }
  35. config := &types.ContainerListOptions{
  36. All: httputils.BoolValue(r, "all"),
  37. Size: httputils.BoolValue(r, "size"),
  38. Since: r.Form.Get("since"),
  39. Before: r.Form.Get("before"),
  40. Filter: filter,
  41. }
  42. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  43. limit, err := strconv.Atoi(tmpLimit)
  44. if err != nil {
  45. return err
  46. }
  47. config.Limit = limit
  48. }
  49. containers, err := s.backend.Containers(config)
  50. if err != nil {
  51. return err
  52. }
  53. return httputils.WriteJSON(w, http.StatusOK, containers)
  54. }
  55. func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  56. if err := httputils.ParseForm(r); err != nil {
  57. return err
  58. }
  59. stream := httputils.BoolValueOrDefault(r, "stream", true)
  60. var out io.Writer
  61. if !stream {
  62. w.Header().Set("Content-Type", "application/json")
  63. out = w
  64. } else {
  65. wf := ioutils.NewWriteFlusher(w)
  66. out = wf
  67. defer wf.Close()
  68. }
  69. var closeNotifier <-chan bool
  70. if notifier, ok := w.(http.CloseNotifier); ok {
  71. closeNotifier = notifier.CloseNotify()
  72. }
  73. config := &backend.ContainerStatsConfig{
  74. Stream: stream,
  75. OutStream: out,
  76. Stop: closeNotifier,
  77. Version: string(httputils.VersionFromContext(ctx)),
  78. }
  79. return s.backend.ContainerStats(vars["name"], config)
  80. }
  81. func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  82. if err := httputils.ParseForm(r); err != nil {
  83. return err
  84. }
  85. // Args are validated before the stream starts because when it starts we're
  86. // sending HTTP 200 by writing an empty chunk of data to tell the client that
  87. // daemon is going to stream. By sending this initial HTTP 200 we can't report
  88. // any error after the stream starts (i.e. container not found, wrong parameters)
  89. // with the appropriate status code.
  90. stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr")
  91. if !(stdout || stderr) {
  92. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  93. }
  94. var closeNotifier <-chan bool
  95. if notifier, ok := w.(http.CloseNotifier); ok {
  96. closeNotifier = notifier.CloseNotify()
  97. }
  98. containerName := vars["name"]
  99. if !s.backend.Exists(containerName) {
  100. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  101. }
  102. // write an empty chunk of data (this is to ensure that the
  103. // HTTP Response is sent immediately, even if the container has
  104. // not yet produced any data)
  105. w.WriteHeader(http.StatusOK)
  106. if flusher, ok := w.(http.Flusher); ok {
  107. flusher.Flush()
  108. }
  109. output := ioutils.NewWriteFlusher(w)
  110. defer output.Close()
  111. logsConfig := &backend.ContainerLogsConfig{
  112. ContainerLogsOptions: types.ContainerLogsOptions{
  113. Follow: httputils.BoolValue(r, "follow"),
  114. Timestamps: httputils.BoolValue(r, "timestamps"),
  115. Since: r.Form.Get("since"),
  116. Tail: r.Form.Get("tail"),
  117. ShowStdout: stdout,
  118. ShowStderr: stderr,
  119. },
  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. var updateConfig container.UpdateConfig
  273. decoder := json.NewDecoder(r.Body)
  274. if err := decoder.Decode(&updateConfig); err != nil {
  275. return err
  276. }
  277. hostConfig := &container.HostConfig{
  278. Resources: updateConfig.Resources,
  279. }
  280. name := vars["name"]
  281. warnings, err := s.backend.ContainerUpdate(name, hostConfig)
  282. if err != nil {
  283. return err
  284. }
  285. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerUpdateResponse{
  286. Warnings: warnings,
  287. })
  288. }
  289. func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  290. if err := httputils.ParseForm(r); err != nil {
  291. return err
  292. }
  293. if err := httputils.CheckForJSON(r); err != nil {
  294. return err
  295. }
  296. name := r.Form.Get("name")
  297. config, hostConfig, networkingConfig, err := runconfig.DecodeContainerConfig(r.Body)
  298. if err != nil {
  299. return err
  300. }
  301. version := httputils.VersionFromContext(ctx)
  302. adjustCPUShares := version.LessThan("1.19")
  303. ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
  304. Name: name,
  305. Config: config,
  306. HostConfig: hostConfig,
  307. NetworkingConfig: networkingConfig,
  308. AdjustCPUShares: adjustCPUShares,
  309. })
  310. if err != nil {
  311. return err
  312. }
  313. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  314. }
  315. func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  316. if err := httputils.ParseForm(r); err != nil {
  317. return err
  318. }
  319. name := vars["name"]
  320. config := &types.ContainerRmConfig{
  321. ForceRemove: httputils.BoolValue(r, "force"),
  322. RemoveVolume: httputils.BoolValue(r, "v"),
  323. RemoveLink: httputils.BoolValue(r, "link"),
  324. }
  325. if err := s.backend.ContainerRm(name, config); err != nil {
  326. // Force a 404 for the empty string
  327. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  328. return fmt.Errorf("no such container: \"\"")
  329. }
  330. return err
  331. }
  332. w.WriteHeader(http.StatusNoContent)
  333. return nil
  334. }
  335. func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  336. if err := httputils.ParseForm(r); err != nil {
  337. return err
  338. }
  339. height, err := strconv.Atoi(r.Form.Get("h"))
  340. if err != nil {
  341. return err
  342. }
  343. width, err := strconv.Atoi(r.Form.Get("w"))
  344. if err != nil {
  345. return err
  346. }
  347. return s.backend.ContainerResize(vars["name"], height, width)
  348. }
  349. func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  350. err := httputils.ParseForm(r)
  351. if err != nil {
  352. return err
  353. }
  354. containerName := vars["name"]
  355. _, upgrade := r.Header["Upgrade"]
  356. keys := []byte{}
  357. detachKeys := r.FormValue("detachKeys")
  358. if detachKeys != "" {
  359. keys, err = term.ToBytes(detachKeys)
  360. if err != nil {
  361. logrus.Warnf("Invalid escape keys provided (%s) using default : ctrl-p ctrl-q", detachKeys)
  362. }
  363. }
  364. attachWithLogsConfig := &backend.ContainerAttachWithLogsConfig{
  365. Hijacker: w.(http.Hijacker),
  366. Upgrade: upgrade,
  367. UseStdin: httputils.BoolValue(r, "stdin"),
  368. UseStdout: httputils.BoolValue(r, "stdout"),
  369. UseStderr: httputils.BoolValue(r, "stderr"),
  370. Logs: httputils.BoolValue(r, "logs"),
  371. Stream: httputils.BoolValue(r, "stream"),
  372. DetachKeys: keys,
  373. }
  374. return s.backend.ContainerAttachWithLogs(containerName, attachWithLogsConfig)
  375. }
  376. func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  377. if err := httputils.ParseForm(r); err != nil {
  378. return err
  379. }
  380. containerName := vars["name"]
  381. if !s.backend.Exists(containerName) {
  382. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  383. }
  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. h := websocket.Handler(func(ws *websocket.Conn) {
  394. defer ws.Close()
  395. wsAttachWithLogsConfig := &backend.ContainerWsAttachWithLogsConfig{
  396. InStream: ws,
  397. OutStream: ws,
  398. ErrStream: ws,
  399. Logs: httputils.BoolValue(r, "logs"),
  400. Stream: httputils.BoolValue(r, "stream"),
  401. DetachKeys: keys,
  402. }
  403. if err := s.backend.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil {
  404. logrus.Errorf("Error attaching websocket: %s", utils.GetErrorMessage(err))
  405. }
  406. })
  407. ws := websocket.Server{Handler: h, Handshake: nil}
  408. ws.ServeHTTP(w, r)
  409. return nil
  410. }