container.go 28 KB

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