container.go 13 KB

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