container.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. package docker
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/dotcloud/docker/rcli"
  6. "github.com/kr/pty"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "strconv"
  14. "syscall"
  15. "time"
  16. )
  17. type Container struct {
  18. root string
  19. Id string
  20. Created time.Time
  21. Path string
  22. Args []string
  23. Config *Config
  24. State State
  25. Image string
  26. network *NetworkInterface
  27. NetworkSettings *NetworkSettings
  28. SysInitPath string
  29. cmd *exec.Cmd
  30. stdout *writeBroadcaster
  31. stderr *writeBroadcaster
  32. stdin io.ReadCloser
  33. stdinPipe io.WriteCloser
  34. ptyStdinMaster io.Closer
  35. ptyStdoutMaster io.Closer
  36. ptyStderrMaster io.Closer
  37. runtime *Runtime
  38. }
  39. type Config struct {
  40. Hostname string
  41. User string
  42. Memory int64 // Memory limit (in bytes)
  43. MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
  44. Detach bool
  45. Ports []int
  46. Tty bool // Attach standard streams to a tty, including stdin if it is not closed.
  47. OpenStdin bool // Open stdin
  48. Env []string
  49. Cmd []string
  50. Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
  51. }
  52. func ParseRun(args []string, stdout io.Writer) (*Config, error) {
  53. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  54. if len(args) > 0 && args[0] != "--help" {
  55. cmd.SetOutput(ioutil.Discard)
  56. }
  57. flUser := cmd.String("u", "", "Username or UID")
  58. flDetach := cmd.Bool("d", false, "Detached mode: leave the container running in the background")
  59. flStdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  60. flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  61. flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  62. var flPorts ports
  63. cmd.Var(&flPorts, "p", "Map a network port to the container")
  64. var flEnv ListOpts
  65. cmd.Var(&flEnv, "e", "Set environment variables")
  66. if err := cmd.Parse(args); err != nil {
  67. return nil, err
  68. }
  69. parsedArgs := cmd.Args()
  70. runCmd := []string{}
  71. image := ""
  72. if len(parsedArgs) >= 1 {
  73. image = cmd.Arg(0)
  74. }
  75. if len(parsedArgs) > 1 {
  76. runCmd = parsedArgs[1:]
  77. }
  78. config := &Config{
  79. Ports: flPorts,
  80. User: *flUser,
  81. Tty: *flTty,
  82. OpenStdin: *flStdin,
  83. Memory: *flMemory,
  84. Detach: *flDetach,
  85. Env: flEnv,
  86. Cmd: runCmd,
  87. Image: image,
  88. }
  89. return config, nil
  90. }
  91. type NetworkSettings struct {
  92. IpAddress string
  93. IpPrefixLen int
  94. Gateway string
  95. PortMapping map[string]string
  96. }
  97. func (container *Container) Cmd() *exec.Cmd {
  98. return container.cmd
  99. }
  100. func (container *Container) When() time.Time {
  101. return container.Created
  102. }
  103. func (container *Container) FromDisk() error {
  104. data, err := ioutil.ReadFile(container.jsonPath())
  105. if err != nil {
  106. return err
  107. }
  108. // Load container settings
  109. if err := json.Unmarshal(data, container); err != nil {
  110. return err
  111. }
  112. return nil
  113. }
  114. func (container *Container) ToDisk() (err error) {
  115. data, err := json.Marshal(container)
  116. if err != nil {
  117. return
  118. }
  119. return ioutil.WriteFile(container.jsonPath(), data, 0666)
  120. }
  121. func (container *Container) generateLXCConfig() error {
  122. fo, err := os.Create(container.lxcConfigPath())
  123. if err != nil {
  124. return err
  125. }
  126. defer fo.Close()
  127. if err := LxcTemplateCompiled.Execute(fo, container); err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. func (container *Container) startPty() error {
  133. stdoutMaster, stdoutSlave, err := pty.Open()
  134. if err != nil {
  135. return err
  136. }
  137. container.ptyStdoutMaster = stdoutMaster
  138. container.cmd.Stdout = stdoutSlave
  139. stderrMaster, stderrSlave, err := pty.Open()
  140. if err != nil {
  141. return err
  142. }
  143. container.ptyStderrMaster = stderrMaster
  144. container.cmd.Stderr = stderrSlave
  145. // Copy the PTYs to our broadcasters
  146. go func() {
  147. defer container.stdout.Close()
  148. Debugf("[startPty] Begin of stdout pipe")
  149. io.Copy(container.stdout, stdoutMaster)
  150. Debugf("[startPty] End of stdout pipe")
  151. }()
  152. go func() {
  153. defer container.stderr.Close()
  154. Debugf("[startPty] Begin of stderr pipe")
  155. io.Copy(container.stderr, stderrMaster)
  156. Debugf("[startPty] End of stderr pipe")
  157. }()
  158. // stdin
  159. var stdinSlave io.ReadCloser
  160. if container.Config.OpenStdin {
  161. stdinMaster, stdinSlave, err := pty.Open()
  162. if err != nil {
  163. return err
  164. }
  165. container.ptyStdinMaster = stdinMaster
  166. container.cmd.Stdin = stdinSlave
  167. // FIXME: The following appears to be broken.
  168. // "cannot set terminal process group (-1): Inappropriate ioctl for device"
  169. // container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
  170. go func() {
  171. defer container.stdin.Close()
  172. Debugf("[startPty] Begin of stdin pipe")
  173. io.Copy(stdinMaster, container.stdin)
  174. Debugf("[startPty] End of stdin pipe")
  175. }()
  176. }
  177. if err := container.cmd.Start(); err != nil {
  178. return err
  179. }
  180. stdoutSlave.Close()
  181. stderrSlave.Close()
  182. if stdinSlave != nil {
  183. stdinSlave.Close()
  184. }
  185. return nil
  186. }
  187. func (container *Container) start() error {
  188. container.cmd.Stdout = container.stdout
  189. container.cmd.Stderr = container.stderr
  190. if container.Config.OpenStdin {
  191. stdin, err := container.cmd.StdinPipe()
  192. if err != nil {
  193. return err
  194. }
  195. go func() {
  196. defer stdin.Close()
  197. Debugf("Begin of stdin pipe [start]")
  198. io.Copy(stdin, container.stdin)
  199. Debugf("End of stdin pipe [start]")
  200. }()
  201. }
  202. return container.cmd.Start()
  203. }
  204. func (container *Container) Start() error {
  205. if err := container.EnsureMounted(); err != nil {
  206. return err
  207. }
  208. if err := container.allocateNetwork(); err != nil {
  209. return err
  210. }
  211. if err := container.generateLXCConfig(); err != nil {
  212. return err
  213. }
  214. params := []string{
  215. "-n", container.Id,
  216. "-f", container.lxcConfigPath(),
  217. "--",
  218. "/sbin/init",
  219. }
  220. // Networking
  221. params = append(params, "-g", container.network.Gateway.String())
  222. // User
  223. if container.Config.User != "" {
  224. params = append(params, "-u", container.Config.User)
  225. }
  226. // Program
  227. params = append(params, "--", container.Path)
  228. params = append(params, container.Args...)
  229. container.cmd = exec.Command("lxc-start", params...)
  230. // Setup environment
  231. container.cmd.Env = append(
  232. []string{
  233. "HOME=/",
  234. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  235. },
  236. container.Config.Env...,
  237. )
  238. // Setup logging of stdout and stderr to disk
  239. if err := container.runtime.LogToDisk(container.stdout, container.logPath("stdout")); err != nil {
  240. return err
  241. }
  242. if err := container.runtime.LogToDisk(container.stderr, container.logPath("stderr")); err != nil {
  243. return err
  244. }
  245. var err error
  246. if container.Config.Tty {
  247. container.cmd.Env = append(
  248. []string{"TERM=xterm"},
  249. container.cmd.Env...,
  250. )
  251. err = container.startPty()
  252. } else {
  253. err = container.start()
  254. }
  255. if err != nil {
  256. return err
  257. }
  258. // FIXME: save state on disk *first*, then converge
  259. // this way disk state is used as a journal, eg. we can restore after crash etc.
  260. container.State.setRunning(container.cmd.Process.Pid)
  261. container.ToDisk()
  262. go container.monitor()
  263. return nil
  264. }
  265. func (container *Container) Run() error {
  266. if err := container.Start(); err != nil {
  267. return err
  268. }
  269. container.Wait()
  270. return nil
  271. }
  272. func (container *Container) Output() (output []byte, err error) {
  273. pipe, err := container.StdoutPipe()
  274. if err != nil {
  275. return nil, err
  276. }
  277. defer pipe.Close()
  278. if err := container.Start(); err != nil {
  279. return nil, err
  280. }
  281. output, err = ioutil.ReadAll(pipe)
  282. container.Wait()
  283. return output, err
  284. }
  285. // StdinPipe() returns a pipe connected to the standard input of the container's
  286. // active process.
  287. //
  288. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  289. return container.stdinPipe, nil
  290. }
  291. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  292. reader, writer := io.Pipe()
  293. container.stdout.AddWriter(writer)
  294. return newBufReader(reader), nil
  295. }
  296. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  297. reader, writer := io.Pipe()
  298. container.stderr.AddWriter(writer)
  299. return newBufReader(reader), nil
  300. }
  301. func (container *Container) allocateNetwork() error {
  302. iface, err := container.runtime.networkManager.Allocate()
  303. if err != nil {
  304. return err
  305. }
  306. container.NetworkSettings.PortMapping = make(map[string]string)
  307. for _, port := range container.Config.Ports {
  308. if extPort, err := iface.AllocatePort(port); err != nil {
  309. iface.Release()
  310. return err
  311. } else {
  312. container.NetworkSettings.PortMapping[strconv.Itoa(port)] = strconv.Itoa(extPort)
  313. }
  314. }
  315. container.network = iface
  316. container.NetworkSettings.IpAddress = iface.IPNet.IP.String()
  317. container.NetworkSettings.IpPrefixLen, _ = iface.IPNet.Mask.Size()
  318. container.NetworkSettings.Gateway = iface.Gateway.String()
  319. return nil
  320. }
  321. func (container *Container) releaseNetwork() error {
  322. err := container.network.Release()
  323. container.network = nil
  324. container.NetworkSettings = &NetworkSettings{}
  325. return err
  326. }
  327. func (container *Container) monitor() {
  328. // Wait for the program to exit
  329. Debugf("Waiting for process")
  330. if err := container.cmd.Wait(); err != nil {
  331. // Discard the error as any signals or non 0 returns will generate an error
  332. Debugf("%s: Process: %s", container.Id, err)
  333. }
  334. Debugf("Process finished")
  335. exitCode := container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
  336. // Cleanup
  337. if err := container.releaseNetwork(); err != nil {
  338. log.Printf("%v: Failed to release network: %v", container.Id, err)
  339. }
  340. if err := container.stdout.Close(); err != nil {
  341. Debugf("%s: Error close stdout: %s", container.Id, err)
  342. }
  343. if err := container.stderr.Close(); err != nil {
  344. Debugf("%s: Error close stderr: %s", container.Id, err)
  345. }
  346. if container.ptyStdinMaster != nil {
  347. if err := container.ptyStdinMaster.Close(); err != nil {
  348. Debugf("%s: Error close pty stdin master: %s", container.Id, err)
  349. }
  350. }
  351. if container.ptyStdoutMaster != nil {
  352. if err := container.ptyStdoutMaster.Close(); err != nil {
  353. Debugf("%s: Error close pty stdout master: %s", container.Id, err)
  354. }
  355. }
  356. if container.ptyStderrMaster != nil {
  357. if err := container.ptyStderrMaster.Close(); err != nil {
  358. Debugf("%s: Error close pty stderr master: %s", container.Id, err)
  359. }
  360. }
  361. if err := container.Unmount(); err != nil {
  362. log.Printf("%v: Failed to umount filesystem: %v", container.Id, err)
  363. }
  364. // Re-create a brand new stdin pipe once the container exited
  365. if container.Config.OpenStdin {
  366. container.stdin, container.stdinPipe = io.Pipe()
  367. }
  368. // Report status back
  369. container.State.setStopped(exitCode)
  370. if err := container.ToDisk(); err != nil {
  371. log.Printf("%s: Failed to dump configuration to the disk: %s", container.Id, err)
  372. }
  373. }
  374. func (container *Container) kill() error {
  375. if container.cmd == nil {
  376. return nil
  377. }
  378. if err := container.cmd.Process.Kill(); err != nil {
  379. return err
  380. }
  381. // Wait for the container to be actually stopped
  382. container.Wait()
  383. return nil
  384. }
  385. func (container *Container) Kill() error {
  386. if !container.State.Running {
  387. return nil
  388. }
  389. return container.kill()
  390. }
  391. func (container *Container) Stop() error {
  392. if !container.State.Running {
  393. return nil
  394. }
  395. // 1. Send a SIGTERM
  396. if output, err := exec.Command("lxc-kill", "-n", container.Id, "15").CombinedOutput(); err != nil {
  397. log.Printf(string(output))
  398. log.Printf("Failed to send SIGTERM to the process, force killing")
  399. if err := container.Kill(); err != nil {
  400. return err
  401. }
  402. }
  403. // 2. Wait for the process to exit on its own
  404. if err := container.WaitTimeout(10 * time.Second); err != nil {
  405. log.Printf("Container %v failed to exit within 10 seconds of SIGTERM - using the force", container.Id)
  406. if err := container.Kill(); err != nil {
  407. return err
  408. }
  409. }
  410. return nil
  411. }
  412. func (container *Container) Restart() error {
  413. if err := container.Stop(); err != nil {
  414. return err
  415. }
  416. if err := container.Start(); err != nil {
  417. return err
  418. }
  419. return nil
  420. }
  421. // Wait blocks until the container stops running, then returns its exit code.
  422. func (container *Container) Wait() int {
  423. for container.State.Running {
  424. container.State.wait()
  425. }
  426. return container.State.ExitCode
  427. }
  428. func (container *Container) ExportRw() (Archive, error) {
  429. return Tar(container.rwPath(), Uncompressed)
  430. }
  431. func (container *Container) Export() (Archive, error) {
  432. if err := container.EnsureMounted(); err != nil {
  433. return nil, err
  434. }
  435. return Tar(container.RootfsPath(), Uncompressed)
  436. }
  437. func (container *Container) WaitTimeout(timeout time.Duration) error {
  438. done := make(chan bool)
  439. go func() {
  440. container.Wait()
  441. done <- true
  442. }()
  443. select {
  444. case <-time.After(timeout):
  445. return fmt.Errorf("Timed Out")
  446. case <-done:
  447. return nil
  448. }
  449. return nil
  450. }
  451. func (container *Container) EnsureMounted() error {
  452. if mounted, err := container.Mounted(); err != nil {
  453. return err
  454. } else if mounted {
  455. return nil
  456. }
  457. return container.Mount()
  458. }
  459. func (container *Container) Mount() error {
  460. image, err := container.GetImage()
  461. if err != nil {
  462. return err
  463. }
  464. return image.Mount(container.RootfsPath(), container.rwPath())
  465. }
  466. func (container *Container) Changes() ([]Change, error) {
  467. image, err := container.GetImage()
  468. if err != nil {
  469. return nil, err
  470. }
  471. return image.Changes(container.rwPath())
  472. }
  473. func (container *Container) GetImage() (*Image, error) {
  474. if container.runtime == nil {
  475. return nil, fmt.Errorf("Can't get image of unregistered container")
  476. }
  477. return container.runtime.graph.Get(container.Image)
  478. }
  479. func (container *Container) Mounted() (bool, error) {
  480. return Mounted(container.RootfsPath())
  481. }
  482. func (container *Container) Unmount() error {
  483. return Unmount(container.RootfsPath())
  484. }
  485. func (container *Container) logPath(name string) string {
  486. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.Id, name))
  487. }
  488. func (container *Container) ReadLog(name string) (io.Reader, error) {
  489. return os.Open(container.logPath(name))
  490. }
  491. func (container *Container) jsonPath() string {
  492. return path.Join(container.root, "config.json")
  493. }
  494. func (container *Container) lxcConfigPath() string {
  495. return path.Join(container.root, "config.lxc")
  496. }
  497. // This method must be exported to be used from the lxc template
  498. func (container *Container) RootfsPath() string {
  499. return path.Join(container.root, "rootfs")
  500. }
  501. func (container *Container) rwPath() string {
  502. return path.Join(container.root, "rw")
  503. }
  504. func validateId(id string) error {
  505. if id == "" {
  506. return fmt.Errorf("Invalid empty id")
  507. }
  508. return nil
  509. }