container.go 19 KB

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