container.go 13 KB

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