container.go 22 KB

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