container.go 13 KB

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