container.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. var (
  305. warnings []string
  306. name = r.Form.Get("name")
  307. )
  308. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  309. if err != nil {
  310. return err
  311. }
  312. version := ctx.Version()
  313. adjustCPUShares := version.LessThan("1.19")
  314. container, warnings, err := s.daemon.ContainerCreate(ctx, name, config, hostConfig, adjustCPUShares)
  315. if err != nil {
  316. return err
  317. }
  318. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  319. ID: container.ID,
  320. Warnings: warnings,
  321. })
  322. }
  323. func (s *Server) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  324. if err := parseForm(r); err != nil {
  325. return err
  326. }
  327. if vars == nil {
  328. return fmt.Errorf("Missing parameter")
  329. }
  330. name := vars["name"]
  331. config := &daemon.ContainerRmConfig{
  332. ForceRemove: boolValue(r, "force"),
  333. RemoveVolume: boolValue(r, "v"),
  334. RemoveLink: boolValue(r, "link"),
  335. }
  336. if err := s.daemon.ContainerRm(ctx, name, config); err != nil {
  337. // Force a 404 for the empty string
  338. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  339. return fmt.Errorf("no such id: \"\"")
  340. }
  341. return err
  342. }
  343. w.WriteHeader(http.StatusNoContent)
  344. return nil
  345. }
  346. func (s *Server) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  347. if err := parseForm(r); err != nil {
  348. return err
  349. }
  350. if vars == nil {
  351. return fmt.Errorf("Missing parameter")
  352. }
  353. height, err := strconv.Atoi(r.Form.Get("h"))
  354. if err != nil {
  355. return err
  356. }
  357. width, err := strconv.Atoi(r.Form.Get("w"))
  358. if err != nil {
  359. return err
  360. }
  361. return s.daemon.ContainerResize(ctx, vars["name"], height, width)
  362. }
  363. func (s *Server) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  364. if err := parseForm(r); err != nil {
  365. return err
  366. }
  367. if vars == nil {
  368. return fmt.Errorf("Missing parameter")
  369. }
  370. containerName := vars["name"]
  371. if !s.daemon.Exists(ctx, containerName) {
  372. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  373. }
  374. inStream, outStream, err := hijackServer(w)
  375. if err != nil {
  376. return err
  377. }
  378. defer closeStreams(inStream, outStream)
  379. if _, ok := r.Header["Upgrade"]; ok {
  380. 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")
  381. } else {
  382. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  383. }
  384. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  385. InStream: inStream,
  386. OutStream: outStream,
  387. UseStdin: boolValue(r, "stdin"),
  388. UseStdout: boolValue(r, "stdout"),
  389. UseStderr: boolValue(r, "stderr"),
  390. Logs: boolValue(r, "logs"),
  391. Stream: boolValue(r, "stream"),
  392. }
  393. if err := s.daemon.ContainerAttachWithLogs(ctx, containerName, attachWithLogsConfig); err != nil {
  394. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  395. }
  396. return nil
  397. }
  398. func (s *Server) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  399. if err := parseForm(r); err != nil {
  400. return err
  401. }
  402. if vars == nil {
  403. return fmt.Errorf("Missing parameter")
  404. }
  405. containerName := vars["name"]
  406. if !s.daemon.Exists(ctx, containerName) {
  407. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  408. }
  409. h := websocket.Handler(func(ws *websocket.Conn) {
  410. defer ws.Close()
  411. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  412. InStream: ws,
  413. OutStream: ws,
  414. ErrStream: ws,
  415. Logs: boolValue(r, "logs"),
  416. Stream: boolValue(r, "stream"),
  417. }
  418. if err := s.daemon.ContainerWsAttachWithLogs(ctx, containerName, wsAttachWithLogsConfig); err != nil {
  419. logrus.Errorf("Error attaching websocket: %s", err)
  420. }
  421. })
  422. ws := websocket.Server{Handler: h, Handshake: nil}
  423. ws.ServeHTTP(w, r)
  424. return nil
  425. }