container.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. if vars == nil {
  52. return fmt.Errorf("Missing parameter")
  53. }
  54. stream := httputils.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. 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. if vars == nil {
  79. return fmt.Errorf("Missing parameter")
  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, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
  93. if err != nil {
  94. return err
  95. }
  96. since = time.Unix(s, 0)
  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.daemon.Exists(containerName) {
  104. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  105. }
  106. outStream := ioutils.NewWriteFlusher(w)
  107. // write an empty chunk of data (this is to ensure that the
  108. // HTTP Response is sent immediately, even if the container has
  109. // not yet produced any data)
  110. outStream.Write(nil)
  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: outStream,
  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. if vars == nil {
  131. return fmt.Errorf("Missing parameter")
  132. }
  133. return s.daemon.ContainerExport(vars["name"], w)
  134. }
  135. func (s *router) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  136. if vars == nil {
  137. return fmt.Errorf("Missing parameter")
  138. }
  139. // If contentLength is -1, we can assumed chunked encoding
  140. // or more technically that the length is unknown
  141. // https://golang.org/src/pkg/net/http/request.go#L139
  142. // net/http otherwise seems to swallow any headers related to chunked encoding
  143. // including r.TransferEncoding
  144. // allow a nil body for backwards compatibility
  145. var hostConfig *runconfig.HostConfig
  146. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  147. if err := httputils.CheckForJSON(r); err != nil {
  148. return err
  149. }
  150. c, err := runconfig.DecodeHostConfig(r.Body)
  151. if err != nil {
  152. return err
  153. }
  154. hostConfig = c
  155. }
  156. if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
  157. return err
  158. }
  159. w.WriteHeader(http.StatusNoContent)
  160. return nil
  161. }
  162. func (s *router) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  163. if err := httputils.ParseForm(r); err != nil {
  164. return err
  165. }
  166. if vars == nil {
  167. return fmt.Errorf("Missing parameter")
  168. }
  169. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  170. if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
  171. return err
  172. }
  173. w.WriteHeader(http.StatusNoContent)
  174. return nil
  175. }
  176. func (s *router) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  177. if vars == nil {
  178. return fmt.Errorf("Missing parameter")
  179. }
  180. if err := httputils.ParseForm(r); err != nil {
  181. return err
  182. }
  183. var sig syscall.Signal
  184. name := vars["name"]
  185. // If we have a signal, look at it. Otherwise, do nothing
  186. if sigStr := r.Form.Get("signal"); sigStr != "" {
  187. var err error
  188. if sig, err = signal.ParseSignal(sigStr); err != nil {
  189. return err
  190. }
  191. }
  192. if err := s.daemon.ContainerKill(name, uint64(sig)); err != nil {
  193. theErr, isDerr := err.(errcode.ErrorCoder)
  194. isStopped := isDerr && theErr.ErrorCode() == derr.ErrorCodeNotRunning
  195. // Return error that's not caused because the container is stopped.
  196. // Return error if the container is not running and the api is >= 1.20
  197. // to keep backwards compatibility.
  198. version := httputils.VersionFromContext(ctx)
  199. if version.GreaterThanOrEqualTo("1.20") || !isStopped {
  200. return fmt.Errorf("Cannot kill container %s: %v", name, err)
  201. }
  202. }
  203. w.WriteHeader(http.StatusNoContent)
  204. return nil
  205. }
  206. func (s *router) postContainersRestart(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 vars == nil {
  211. return fmt.Errorf("Missing parameter")
  212. }
  213. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  214. if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
  215. return err
  216. }
  217. w.WriteHeader(http.StatusNoContent)
  218. return nil
  219. }
  220. func (s *router) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  221. if vars == nil {
  222. return fmt.Errorf("Missing parameter")
  223. }
  224. if err := httputils.ParseForm(r); err != nil {
  225. return err
  226. }
  227. if err := s.daemon.ContainerPause(vars["name"]); err != nil {
  228. return err
  229. }
  230. w.WriteHeader(http.StatusNoContent)
  231. return nil
  232. }
  233. func (s *router) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  234. if vars == nil {
  235. return fmt.Errorf("Missing parameter")
  236. }
  237. if err := httputils.ParseForm(r); err != nil {
  238. return err
  239. }
  240. if err := s.daemon.ContainerUnpause(vars["name"]); err != nil {
  241. return err
  242. }
  243. w.WriteHeader(http.StatusNoContent)
  244. return nil
  245. }
  246. func (s *router) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  247. if vars == nil {
  248. return fmt.Errorf("Missing parameter")
  249. }
  250. status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
  251. if err != nil {
  252. return err
  253. }
  254. return httputils.WriteJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  255. StatusCode: status,
  256. })
  257. }
  258. func (s *router) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  259. if vars == nil {
  260. return fmt.Errorf("Missing parameter")
  261. }
  262. changes, err := s.daemon.ContainerChanges(vars["name"])
  263. if err != nil {
  264. return err
  265. }
  266. return httputils.WriteJSON(w, http.StatusOK, changes)
  267. }
  268. func (s *router) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  269. if vars == nil {
  270. return fmt.Errorf("Missing parameter")
  271. }
  272. if err := httputils.ParseForm(r); err != nil {
  273. return err
  274. }
  275. procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  276. if err != nil {
  277. return err
  278. }
  279. return httputils.WriteJSON(w, http.StatusOK, procList)
  280. }
  281. func (s *router) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  282. if err := httputils.ParseForm(r); err != nil {
  283. return err
  284. }
  285. if vars == nil {
  286. return fmt.Errorf("Missing parameter")
  287. }
  288. name := vars["name"]
  289. newName := r.Form.Get("name")
  290. if err := s.daemon.ContainerRename(name, newName); err != nil {
  291. return err
  292. }
  293. w.WriteHeader(http.StatusNoContent)
  294. return nil
  295. }
  296. func (s *router) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  297. if err := httputils.ParseForm(r); err != nil {
  298. return err
  299. }
  300. if err := httputils.CheckForJSON(r); err != nil {
  301. return err
  302. }
  303. name := r.Form.Get("name")
  304. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  305. if err != nil {
  306. return err
  307. }
  308. version := httputils.VersionFromContext(ctx)
  309. adjustCPUShares := version.LessThan("1.19")
  310. ccr, err := s.daemon.ContainerCreate(name, config, hostConfig, adjustCPUShares)
  311. if err != nil {
  312. return err
  313. }
  314. return httputils.WriteJSON(w, http.StatusCreated, ccr)
  315. }
  316. func (s *router) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  317. if err := httputils.ParseForm(r); err != nil {
  318. return err
  319. }
  320. if vars == nil {
  321. return fmt.Errorf("Missing parameter")
  322. }
  323. name := vars["name"]
  324. config := &daemon.ContainerRmConfig{
  325. ForceRemove: httputils.BoolValue(r, "force"),
  326. RemoveVolume: httputils.BoolValue(r, "v"),
  327. RemoveLink: httputils.BoolValue(r, "link"),
  328. }
  329. if err := s.daemon.ContainerRm(name, config); err != nil {
  330. // Force a 404 for the empty string
  331. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  332. return fmt.Errorf("no such id: \"\"")
  333. }
  334. return err
  335. }
  336. w.WriteHeader(http.StatusNoContent)
  337. return nil
  338. }
  339. func (s *router) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  340. if err := httputils.ParseForm(r); err != nil {
  341. return err
  342. }
  343. if vars == nil {
  344. return fmt.Errorf("Missing parameter")
  345. }
  346. height, err := strconv.Atoi(r.Form.Get("h"))
  347. if err != nil {
  348. return err
  349. }
  350. width, err := strconv.Atoi(r.Form.Get("w"))
  351. if err != nil {
  352. return err
  353. }
  354. return s.daemon.ContainerResize(vars["name"], height, width)
  355. }
  356. func (s *router) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  357. if err := httputils.ParseForm(r); err != nil {
  358. return err
  359. }
  360. if vars == nil {
  361. return fmt.Errorf("Missing parameter")
  362. }
  363. containerName := vars["name"]
  364. if !s.daemon.Exists(containerName) {
  365. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  366. }
  367. inStream, outStream, err := httputils.HijackConnection(w)
  368. if err != nil {
  369. return err
  370. }
  371. defer httputils.CloseStreams(inStream, outStream)
  372. if _, ok := r.Header["Upgrade"]; ok {
  373. 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")
  374. } else {
  375. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  376. }
  377. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  378. InStream: inStream,
  379. OutStream: outStream,
  380. UseStdin: httputils.BoolValue(r, "stdin"),
  381. UseStdout: httputils.BoolValue(r, "stdout"),
  382. UseStderr: httputils.BoolValue(r, "stderr"),
  383. Logs: httputils.BoolValue(r, "logs"),
  384. Stream: httputils.BoolValue(r, "stream"),
  385. }
  386. if err := s.daemon.ContainerAttachWithLogs(containerName, attachWithLogsConfig); err != nil {
  387. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  388. }
  389. return nil
  390. }
  391. func (s *router) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  392. if err := httputils.ParseForm(r); err != nil {
  393. return err
  394. }
  395. if vars == nil {
  396. return fmt.Errorf("Missing parameter")
  397. }
  398. containerName := vars["name"]
  399. if !s.daemon.Exists(containerName) {
  400. return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
  401. }
  402. h := websocket.Handler(func(ws *websocket.Conn) {
  403. defer ws.Close()
  404. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  405. InStream: ws,
  406. OutStream: ws,
  407. ErrStream: ws,
  408. Logs: httputils.BoolValue(r, "logs"),
  409. Stream: httputils.BoolValue(r, "stream"),
  410. }
  411. if err := s.daemon.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil {
  412. logrus.Errorf("Error attaching websocket: %s", err)
  413. }
  414. })
  415. ws := websocket.Server{Handler: h, Handshake: nil}
  416. ws.ServeHTTP(w, r)
  417. return nil
  418. }