container.go 27 KB

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