container.go 13 KB

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