container.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. "sort"
  14. "strconv"
  15. "strings"
  16. "syscall"
  17. "time"
  18. )
  19. type Container struct {
  20. root string
  21. Id string
  22. Created time.Time
  23. Path string
  24. Args []string
  25. Config *Config
  26. State State
  27. Image string
  28. network *NetworkInterface
  29. NetworkSettings *NetworkSettings
  30. SysInitPath string
  31. ResolvConfPath string
  32. cmd *exec.Cmd
  33. stdout *writeBroadcaster
  34. stderr *writeBroadcaster
  35. stdin io.ReadCloser
  36. stdinPipe io.WriteCloser
  37. ptyMaster io.Closer
  38. runtime *Runtime
  39. waitLock chan struct{}
  40. }
  41. type Config struct {
  42. Hostname string
  43. User string
  44. Memory int64 // Memory limit (in bytes)
  45. MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
  46. AttachStdin bool
  47. AttachStdout bool
  48. AttachStderr bool
  49. PortSpecs []string
  50. Tty bool // Attach standard streams to a tty, including stdin if it is not closed.
  51. OpenStdin bool // Open stdin
  52. StdinOnce bool // If true, close stdin after the 1 attached client disconnects.
  53. Env []string
  54. Cmd []string
  55. Dns []string
  56. Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
  57. }
  58. func ParseRun(args []string, stdout io.Writer, capabilities *Capabilities) (*Config, error) {
  59. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  60. if len(args) > 0 && args[0] != "--help" {
  61. cmd.SetOutput(ioutil.Discard)
  62. }
  63. flHostname := cmd.String("h", "", "Container host name")
  64. flUser := cmd.String("u", "", "Username or UID")
  65. flDetach := cmd.Bool("d", false, "Detached mode: leave the container running in the background")
  66. flAttach := NewAttachOpts()
  67. cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.")
  68. flStdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  69. flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  70. flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  71. if *flMemory > 0 && !capabilities.MemoryLimit {
  72. fmt.Fprintf(stdout, "WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  73. *flMemory = 0
  74. }
  75. var flPorts ListOpts
  76. cmd.Var(&flPorts, "p", "Expose a container's port to the host (use 'docker port' to see the actual mapping)")
  77. var flEnv ListOpts
  78. cmd.Var(&flEnv, "e", "Set environment variables")
  79. var flDns ListOpts
  80. cmd.Var(&flDns, "dns", "Set custom dns servers")
  81. if err := cmd.Parse(args); err != nil {
  82. return nil, err
  83. }
  84. if *flDetach && len(flAttach) > 0 {
  85. return nil, fmt.Errorf("Conflicting options: -a and -d")
  86. }
  87. // If neither -d or -a are set, attach to everything by default
  88. if len(flAttach) == 0 && !*flDetach {
  89. if !*flDetach {
  90. flAttach.Set("stdout")
  91. flAttach.Set("stderr")
  92. if *flStdin {
  93. flAttach.Set("stdin")
  94. }
  95. }
  96. }
  97. parsedArgs := cmd.Args()
  98. runCmd := []string{}
  99. image := ""
  100. if len(parsedArgs) >= 1 {
  101. image = cmd.Arg(0)
  102. }
  103. if len(parsedArgs) > 1 {
  104. runCmd = parsedArgs[1:]
  105. }
  106. config := &Config{
  107. Hostname: *flHostname,
  108. PortSpecs: flPorts,
  109. User: *flUser,
  110. Tty: *flTty,
  111. OpenStdin: *flStdin,
  112. Memory: *flMemory,
  113. AttachStdin: flAttach.Get("stdin"),
  114. AttachStdout: flAttach.Get("stdout"),
  115. AttachStderr: flAttach.Get("stderr"),
  116. Env: flEnv,
  117. Cmd: runCmd,
  118. Dns: flDns,
  119. Image: image,
  120. }
  121. if *flMemory > 0 && !capabilities.SwapLimit {
  122. fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  123. config.MemorySwap = -1
  124. }
  125. // When allocating stdin in attached mode, close stdin at client disconnect
  126. if config.OpenStdin && config.AttachStdin {
  127. config.StdinOnce = true
  128. }
  129. return config, nil
  130. }
  131. type NetworkSettings struct {
  132. IpAddress string
  133. IpPrefixLen int
  134. Gateway string
  135. Bridge string
  136. PortMapping map[string]string
  137. }
  138. // String returns a human-readable description of the port mapping defined in the settings
  139. func (settings *NetworkSettings) PortMappingHuman() string {
  140. var mapping []string
  141. for private, public := range settings.PortMapping {
  142. mapping = append(mapping, fmt.Sprintf("%s->%s", public, private))
  143. }
  144. sort.Strings(mapping)
  145. return strings.Join(mapping, ", ")
  146. }
  147. func (container *Container) Cmd() *exec.Cmd {
  148. return container.cmd
  149. }
  150. func (container *Container) When() time.Time {
  151. return container.Created
  152. }
  153. func (container *Container) FromDisk() error {
  154. data, err := ioutil.ReadFile(container.jsonPath())
  155. if err != nil {
  156. return err
  157. }
  158. // Load container settings
  159. if err := json.Unmarshal(data, container); err != nil {
  160. return err
  161. }
  162. return nil
  163. }
  164. func (container *Container) ToDisk() (err error) {
  165. data, err := json.Marshal(container)
  166. if err != nil {
  167. return
  168. }
  169. return ioutil.WriteFile(container.jsonPath(), data, 0666)
  170. }
  171. func (container *Container) generateLXCConfig() error {
  172. fo, err := os.Create(container.lxcConfigPath())
  173. if err != nil {
  174. return err
  175. }
  176. defer fo.Close()
  177. if err := LxcTemplateCompiled.Execute(fo, container); err != nil {
  178. return err
  179. }
  180. return nil
  181. }
  182. func (container *Container) startPty() error {
  183. ptyMaster, ptySlave, err := pty.Open()
  184. if err != nil {
  185. return err
  186. }
  187. container.ptyMaster = ptyMaster
  188. container.cmd.Stdout = ptySlave
  189. container.cmd.Stderr = ptySlave
  190. // Copy the PTYs to our broadcasters
  191. go func() {
  192. defer container.stdout.CloseWriters()
  193. Debugf("[startPty] Begin of stdout pipe")
  194. io.Copy(container.stdout, ptyMaster)
  195. Debugf("[startPty] End of stdout pipe")
  196. }()
  197. // stdin
  198. if container.Config.OpenStdin {
  199. container.cmd.Stdin = ptySlave
  200. container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
  201. go func() {
  202. defer container.stdin.Close()
  203. Debugf("[startPty] Begin of stdin pipe")
  204. io.Copy(ptyMaster, container.stdin)
  205. Debugf("[startPty] End of stdin pipe")
  206. }()
  207. }
  208. if err := container.cmd.Start(); err != nil {
  209. return err
  210. }
  211. ptySlave.Close()
  212. return nil
  213. }
  214. func (container *Container) start() error {
  215. container.cmd.Stdout = container.stdout
  216. container.cmd.Stderr = container.stderr
  217. if container.Config.OpenStdin {
  218. stdin, err := container.cmd.StdinPipe()
  219. if err != nil {
  220. return err
  221. }
  222. go func() {
  223. defer stdin.Close()
  224. Debugf("Begin of stdin pipe [start]")
  225. io.Copy(stdin, container.stdin)
  226. Debugf("End of stdin pipe [start]")
  227. }()
  228. }
  229. return container.cmd.Start()
  230. }
  231. func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error {
  232. var cStdout, cStderr io.ReadCloser
  233. var nJobs int
  234. errors := make(chan error, 3)
  235. if stdin != nil && container.Config.OpenStdin {
  236. nJobs += 1
  237. if cStdin, err := container.StdinPipe(); err != nil {
  238. errors <- err
  239. } else {
  240. go func() {
  241. Debugf("[start] attach stdin\n")
  242. defer Debugf("[end] attach stdin\n")
  243. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  244. if cStdout != nil {
  245. defer cStdout.Close()
  246. }
  247. if cStderr != nil {
  248. defer cStderr.Close()
  249. }
  250. if container.Config.StdinOnce && !container.Config.Tty {
  251. defer cStdin.Close()
  252. }
  253. if container.Config.Tty {
  254. _, err = CopyEscapable(cStdin, stdin)
  255. } else {
  256. _, err = io.Copy(cStdin, stdin)
  257. }
  258. if err != nil {
  259. Debugf("[error] attach stdin: %s\n", err)
  260. }
  261. // Discard error, expecting pipe error
  262. errors <- nil
  263. }()
  264. }
  265. }
  266. if stdout != nil {
  267. nJobs += 1
  268. if p, err := container.StdoutPipe(); err != nil {
  269. errors <- err
  270. } else {
  271. cStdout = p
  272. go func() {
  273. Debugf("[start] attach stdout\n")
  274. defer Debugf("[end] attach stdout\n")
  275. // If we are in StdinOnce mode, then close stdin
  276. if container.Config.StdinOnce {
  277. if stdin != nil {
  278. defer stdin.Close()
  279. }
  280. if stdinCloser != nil {
  281. defer stdinCloser.Close()
  282. }
  283. }
  284. _, err := io.Copy(stdout, cStdout)
  285. if err != nil {
  286. Debugf("[error] attach stdout: %s\n", err)
  287. }
  288. errors <- err
  289. }()
  290. }
  291. }
  292. if stderr != nil {
  293. nJobs += 1
  294. if p, err := container.StderrPipe(); err != nil {
  295. errors <- err
  296. } else {
  297. cStderr = p
  298. go func() {
  299. Debugf("[start] attach stderr\n")
  300. defer Debugf("[end] attach stderr\n")
  301. // If we are in StdinOnce mode, then close stdin
  302. if container.Config.StdinOnce {
  303. if stdin != nil {
  304. defer stdin.Close()
  305. }
  306. if stdinCloser != nil {
  307. defer stdinCloser.Close()
  308. }
  309. }
  310. _, err := io.Copy(stderr, cStderr)
  311. if err != nil {
  312. Debugf("[error] attach stderr: %s\n", err)
  313. }
  314. errors <- err
  315. }()
  316. }
  317. }
  318. return Go(func() error {
  319. if cStdout != nil {
  320. defer cStdout.Close()
  321. }
  322. if cStderr != nil {
  323. defer cStderr.Close()
  324. }
  325. // FIXME: how do clean up the stdin goroutine without the unwanted side effect
  326. // of closing the passed stdin? Add an intermediary io.Pipe?
  327. for i := 0; i < nJobs; i += 1 {
  328. Debugf("Waiting for job %d/%d\n", i+1, nJobs)
  329. if err := <-errors; err != nil {
  330. Debugf("Job %d returned error %s. Aborting all jobs\n", i+1, err)
  331. return err
  332. }
  333. Debugf("Job %d completed successfully\n", i+1)
  334. }
  335. Debugf("All jobs completed successfully\n")
  336. return nil
  337. })
  338. }
  339. func (container *Container) Start() error {
  340. container.State.lock()
  341. defer container.State.unlock()
  342. if container.State.Running {
  343. return fmt.Errorf("The container %s is already running.", container.Id)
  344. }
  345. if err := container.EnsureMounted(); err != nil {
  346. return err
  347. }
  348. if err := container.allocateNetwork(); err != nil {
  349. return err
  350. }
  351. // Make sure the config is compatible with the current kernel
  352. if container.Config.Memory > 0 && !container.runtime.capabilities.MemoryLimit {
  353. log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  354. container.Config.Memory = 0
  355. }
  356. if container.Config.Memory > 0 && !container.runtime.capabilities.SwapLimit {
  357. log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  358. container.Config.MemorySwap = -1
  359. }
  360. if err := container.generateLXCConfig(); err != nil {
  361. return err
  362. }
  363. params := []string{
  364. "-n", container.Id,
  365. "-f", container.lxcConfigPath(),
  366. "--",
  367. "/sbin/init",
  368. }
  369. // Networking
  370. params = append(params, "-g", container.network.Gateway.String())
  371. // User
  372. if container.Config.User != "" {
  373. params = append(params, "-u", container.Config.User)
  374. }
  375. if container.Config.Tty {
  376. params = append(params, "-e", "TERM=xterm")
  377. }
  378. // Setup environment
  379. params = append(params,
  380. "-e", "HOME=/",
  381. "-e", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  382. )
  383. for _, elem := range container.Config.Env {
  384. params = append(params, "-e", elem)
  385. }
  386. // Program
  387. params = append(params, "--", container.Path)
  388. params = append(params, container.Args...)
  389. container.cmd = exec.Command("lxc-start", params...)
  390. // Setup logging of stdout and stderr to disk
  391. if err := container.runtime.LogToDisk(container.stdout, container.logPath("stdout")); err != nil {
  392. return err
  393. }
  394. if err := container.runtime.LogToDisk(container.stderr, container.logPath("stderr")); err != nil {
  395. return err
  396. }
  397. var err error
  398. if container.Config.Tty {
  399. err = container.startPty()
  400. } else {
  401. err = container.start()
  402. }
  403. if err != nil {
  404. return err
  405. }
  406. // FIXME: save state on disk *first*, then converge
  407. // this way disk state is used as a journal, eg. we can restore after crash etc.
  408. container.State.setRunning(container.cmd.Process.Pid)
  409. // Init the lock
  410. container.waitLock = make(chan struct{})
  411. container.ToDisk()
  412. go container.monitor()
  413. return nil
  414. }
  415. func (container *Container) Run() error {
  416. if err := container.Start(); err != nil {
  417. return err
  418. }
  419. container.Wait()
  420. return nil
  421. }
  422. func (container *Container) Output() (output []byte, err error) {
  423. pipe, err := container.StdoutPipe()
  424. if err != nil {
  425. return nil, err
  426. }
  427. defer pipe.Close()
  428. if err := container.Start(); err != nil {
  429. return nil, err
  430. }
  431. output, err = ioutil.ReadAll(pipe)
  432. container.Wait()
  433. return output, err
  434. }
  435. // StdinPipe() returns a pipe connected to the standard input of the container's
  436. // active process.
  437. //
  438. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  439. return container.stdinPipe, nil
  440. }
  441. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  442. reader, writer := io.Pipe()
  443. container.stdout.AddWriter(writer)
  444. return newBufReader(reader), nil
  445. }
  446. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  447. reader, writer := io.Pipe()
  448. container.stderr.AddWriter(writer)
  449. return newBufReader(reader), nil
  450. }
  451. func (container *Container) allocateNetwork() error {
  452. iface, err := container.runtime.networkManager.Allocate()
  453. if err != nil {
  454. return err
  455. }
  456. container.NetworkSettings.PortMapping = make(map[string]string)
  457. for _, spec := range container.Config.PortSpecs {
  458. if nat, err := iface.AllocatePort(spec); err != nil {
  459. iface.Release()
  460. return err
  461. } else {
  462. container.NetworkSettings.PortMapping[strconv.Itoa(nat.Backend)] = strconv.Itoa(nat.Frontend)
  463. }
  464. }
  465. container.network = iface
  466. container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface
  467. container.NetworkSettings.IpAddress = iface.IPNet.IP.String()
  468. container.NetworkSettings.IpPrefixLen, _ = iface.IPNet.Mask.Size()
  469. container.NetworkSettings.Gateway = iface.Gateway.String()
  470. return nil
  471. }
  472. func (container *Container) releaseNetwork() {
  473. container.network.Release()
  474. container.network = nil
  475. container.NetworkSettings = &NetworkSettings{}
  476. }
  477. // FIXME: replace this with a control socket within docker-init
  478. func (container *Container) waitLxc() error {
  479. for {
  480. if output, err := exec.Command("lxc-info", "-n", container.Id).CombinedOutput(); err != nil {
  481. return err
  482. } else {
  483. if !strings.Contains(string(output), "RUNNING") {
  484. return nil
  485. }
  486. }
  487. time.Sleep(500 * time.Millisecond)
  488. }
  489. return nil
  490. }
  491. func (container *Container) monitor() {
  492. // Wait for the program to exit
  493. Debugf("Waiting for process")
  494. // If the command does not exists, try to wait via lxc
  495. if container.cmd == nil {
  496. if err := container.waitLxc(); err != nil {
  497. Debugf("%s: Process: %s", container.Id, err)
  498. }
  499. } else {
  500. if err := container.cmd.Wait(); err != nil {
  501. // Discard the error as any signals or non 0 returns will generate an error
  502. Debugf("%s: Process: %s", container.Id, err)
  503. }
  504. }
  505. Debugf("Process finished")
  506. var exitCode int = -1
  507. if container.cmd != nil {
  508. exitCode = container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
  509. }
  510. // Cleanup
  511. container.releaseNetwork()
  512. if container.Config.OpenStdin {
  513. if err := container.stdin.Close(); err != nil {
  514. Debugf("%s: Error close stdin: %s", container.Id, err)
  515. }
  516. }
  517. if err := container.stdout.CloseWriters(); err != nil {
  518. Debugf("%s: Error close stdout: %s", container.Id, err)
  519. }
  520. if err := container.stderr.CloseWriters(); err != nil {
  521. Debugf("%s: Error close stderr: %s", container.Id, err)
  522. }
  523. if container.ptyMaster != nil {
  524. if err := container.ptyMaster.Close(); err != nil {
  525. Debugf("%s: Error closing Pty master: %s", container.Id, err)
  526. }
  527. }
  528. if err := container.Unmount(); err != nil {
  529. log.Printf("%v: Failed to umount filesystem: %v", container.Id, err)
  530. }
  531. // Re-create a brand new stdin pipe once the container exited
  532. if container.Config.OpenStdin {
  533. container.stdin, container.stdinPipe = io.Pipe()
  534. }
  535. // Report status back
  536. container.State.setStopped(exitCode)
  537. // Release the lock
  538. close(container.waitLock)
  539. if err := container.ToDisk(); err != nil {
  540. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  541. // If another goroutine was waiting for Wait() to return before removing the container's root
  542. // from the filesystem... At this point it may already have done so.
  543. // This is because State.setStopped() has already been called, and has caused Wait()
  544. // to return.
  545. // FIXME: why are we serializing running state to disk in the first place?
  546. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.Id, err)
  547. }
  548. }
  549. func (container *Container) kill() error {
  550. if !container.State.Running {
  551. return nil
  552. }
  553. // Sending SIGKILL to the process via lxc
  554. output, err := exec.Command("lxc-kill", "-n", container.Id, "9").CombinedOutput()
  555. if err != nil {
  556. log.Printf("error killing container %s (%s, %s)", container.Id, output, err)
  557. }
  558. // 2. Wait for the process to die, in last resort, try to kill the process directly
  559. if err := container.WaitTimeout(10 * time.Second); err != nil {
  560. if container.cmd == nil {
  561. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", container.Id)
  562. }
  563. log.Printf("Container %s failed to exit within 10 seconds of lxc SIGKILL - trying direct SIGKILL", container.Id)
  564. if err := container.cmd.Process.Kill(); err != nil {
  565. return err
  566. }
  567. }
  568. // Wait for the container to be actually stopped
  569. container.Wait()
  570. return nil
  571. }
  572. func (container *Container) Kill() error {
  573. container.State.lock()
  574. defer container.State.unlock()
  575. if !container.State.Running {
  576. return nil
  577. }
  578. if container.State.Ghost {
  579. return fmt.Errorf("Can't kill ghost container")
  580. }
  581. return container.kill()
  582. }
  583. func (container *Container) Stop(seconds int) error {
  584. container.State.lock()
  585. defer container.State.unlock()
  586. if !container.State.Running {
  587. return nil
  588. }
  589. if container.State.Ghost {
  590. return fmt.Errorf("Can't stop ghost container")
  591. }
  592. // 1. Send a SIGTERM
  593. if output, err := exec.Command("lxc-kill", "-n", container.Id, "15").CombinedOutput(); err != nil {
  594. log.Print(string(output))
  595. log.Print("Failed to send SIGTERM to the process, force killing")
  596. if err := container.kill(); err != nil {
  597. return err
  598. }
  599. }
  600. // 2. Wait for the process to exit on its own
  601. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  602. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.Id, seconds)
  603. if err := container.kill(); err != nil {
  604. return err
  605. }
  606. }
  607. return nil
  608. }
  609. func (container *Container) Restart(seconds int) error {
  610. if err := container.Stop(seconds); err != nil {
  611. return err
  612. }
  613. if err := container.Start(); err != nil {
  614. return err
  615. }
  616. return nil
  617. }
  618. // Wait blocks until the container stops running, then returns its exit code.
  619. func (container *Container) Wait() int {
  620. <-container.waitLock
  621. return container.State.ExitCode
  622. }
  623. func (container *Container) ExportRw() (Archive, error) {
  624. return Tar(container.rwPath(), Uncompressed)
  625. }
  626. func (container *Container) Export() (Archive, error) {
  627. if err := container.EnsureMounted(); err != nil {
  628. return nil, err
  629. }
  630. return Tar(container.RootfsPath(), Uncompressed)
  631. }
  632. func (container *Container) WaitTimeout(timeout time.Duration) error {
  633. done := make(chan bool)
  634. go func() {
  635. container.Wait()
  636. done <- true
  637. }()
  638. select {
  639. case <-time.After(timeout):
  640. return fmt.Errorf("Timed Out")
  641. case <-done:
  642. return nil
  643. }
  644. panic("unreachable")
  645. }
  646. func (container *Container) EnsureMounted() error {
  647. if mounted, err := container.Mounted(); err != nil {
  648. return err
  649. } else if mounted {
  650. return nil
  651. }
  652. return container.Mount()
  653. }
  654. func (container *Container) Mount() error {
  655. image, err := container.GetImage()
  656. if err != nil {
  657. return err
  658. }
  659. return image.Mount(container.RootfsPath(), container.rwPath())
  660. }
  661. func (container *Container) Changes() ([]Change, error) {
  662. image, err := container.GetImage()
  663. if err != nil {
  664. return nil, err
  665. }
  666. return image.Changes(container.rwPath())
  667. }
  668. func (container *Container) GetImage() (*Image, error) {
  669. if container.runtime == nil {
  670. return nil, fmt.Errorf("Can't get image of unregistered container")
  671. }
  672. return container.runtime.graph.Get(container.Image)
  673. }
  674. func (container *Container) Mounted() (bool, error) {
  675. return Mounted(container.RootfsPath())
  676. }
  677. func (container *Container) Unmount() error {
  678. return Unmount(container.RootfsPath())
  679. }
  680. // ShortId returns a shorthand version of the container's id for convenience.
  681. // A collision with other container shorthands is very unlikely, but possible.
  682. // In case of a collision a lookup with Runtime.Get() will fail, and the caller
  683. // will need to use a langer prefix, or the full-length container Id.
  684. func (container *Container) ShortId() string {
  685. return TruncateId(container.Id)
  686. }
  687. func (container *Container) logPath(name string) string {
  688. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.Id, name))
  689. }
  690. func (container *Container) ReadLog(name string) (io.Reader, error) {
  691. return os.Open(container.logPath(name))
  692. }
  693. func (container *Container) jsonPath() string {
  694. return path.Join(container.root, "config.json")
  695. }
  696. func (container *Container) lxcConfigPath() string {
  697. return path.Join(container.root, "config.lxc")
  698. }
  699. // This method must be exported to be used from the lxc template
  700. func (container *Container) RootfsPath() string {
  701. return path.Join(container.root, "rootfs")
  702. }
  703. func (container *Container) rwPath() string {
  704. return path.Join(container.root, "rw")
  705. }
  706. func validateId(id string) error {
  707. if id == "" {
  708. return fmt.Errorf("Invalid empty id")
  709. }
  710. return nil
  711. }