container_routes.go 13 KB

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