container_routes.go 14 KB

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