container.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. package docker
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/dotcloud/docker/archive"
  7. "github.com/dotcloud/docker/engine"
  8. "github.com/dotcloud/docker/execdriver"
  9. "github.com/dotcloud/docker/graphdriver"
  10. "github.com/dotcloud/docker/links"
  11. "github.com/dotcloud/docker/nat"
  12. "github.com/dotcloud/docker/runconfig"
  13. "github.com/dotcloud/docker/utils"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "os"
  18. "path"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. )
  24. var (
  25. ErrNotATTY = errors.New("The PTY is not a file")
  26. ErrNoTTY = errors.New("No PTY found")
  27. ErrContainerStart = errors.New("The container failed to start. Unknown error")
  28. ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.")
  29. )
  30. type Container struct {
  31. sync.Mutex
  32. root string // Path to the "home" of the container, including metadata.
  33. basefs string // Path to the graphdriver mountpoint
  34. ID string
  35. Created time.Time
  36. Path string
  37. Args []string
  38. Config *runconfig.Config
  39. State State
  40. Image string
  41. NetworkSettings *NetworkSettings
  42. ResolvConfPath string
  43. HostnamePath string
  44. HostsPath string
  45. Name string
  46. Driver string
  47. command *execdriver.Command
  48. stdout *utils.WriteBroadcaster
  49. stderr *utils.WriteBroadcaster
  50. stdin io.ReadCloser
  51. stdinPipe io.WriteCloser
  52. runtime *Runtime
  53. waitLock chan struct{}
  54. Volumes map[string]string
  55. // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk.
  56. // Easier than migrating older container configs :)
  57. VolumesRW map[string]bool
  58. hostConfig *runconfig.HostConfig
  59. activeLinks map[string]*links.Link
  60. }
  61. // FIXME: move deprecated port stuff to nat to clean up the core.
  62. type PortMapping map[string]string // Deprecated
  63. type NetworkSettings struct {
  64. IPAddress string
  65. IPPrefixLen int
  66. Gateway string
  67. Bridge string
  68. PortMapping map[string]PortMapping // Deprecated
  69. Ports nat.PortMap
  70. }
  71. func (settings *NetworkSettings) PortMappingAPI() *engine.Table {
  72. var outs = engine.NewTable("", 0)
  73. for port, bindings := range settings.Ports {
  74. p, _ := nat.ParsePort(port.Port())
  75. if len(bindings) == 0 {
  76. out := &engine.Env{}
  77. out.SetInt("PublicPort", p)
  78. out.Set("Type", port.Proto())
  79. outs.Add(out)
  80. continue
  81. }
  82. for _, binding := range bindings {
  83. out := &engine.Env{}
  84. h, _ := nat.ParsePort(binding.HostPort)
  85. out.SetInt("PrivatePort", p)
  86. out.SetInt("PublicPort", h)
  87. out.Set("Type", port.Proto())
  88. out.Set("IP", binding.HostIp)
  89. outs.Add(out)
  90. }
  91. }
  92. return outs
  93. }
  94. // Inject the io.Reader at the given path. Note: do not close the reader
  95. func (container *Container) Inject(file io.Reader, pth string) error {
  96. if err := container.Mount(); err != nil {
  97. return fmt.Errorf("inject: error mounting container %s: %s", container.ID, err)
  98. }
  99. defer container.Unmount()
  100. // Return error if path exists
  101. destPath := path.Join(container.basefs, pth)
  102. if _, err := os.Stat(destPath); err == nil {
  103. // Since err is nil, the path could be stat'd and it exists
  104. return fmt.Errorf("%s exists", pth)
  105. } else if !os.IsNotExist(err) {
  106. // Expect err might be that the file doesn't exist, so
  107. // if it's some other error, return that.
  108. return err
  109. }
  110. // Make sure the directory exists
  111. if err := os.MkdirAll(path.Join(container.basefs, path.Dir(pth)), 0755); err != nil {
  112. return err
  113. }
  114. dest, err := os.Create(destPath)
  115. if err != nil {
  116. return err
  117. }
  118. defer dest.Close()
  119. if _, err := io.Copy(dest, file); err != nil {
  120. return err
  121. }
  122. return nil
  123. }
  124. func (container *Container) When() time.Time {
  125. return container.Created
  126. }
  127. func (container *Container) FromDisk() error {
  128. data, err := ioutil.ReadFile(container.jsonPath())
  129. if err != nil {
  130. return err
  131. }
  132. // Load container settings
  133. // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it
  134. if err := json.Unmarshal(data, container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
  135. return err
  136. }
  137. return container.readHostConfig()
  138. }
  139. func (container *Container) ToDisk() (err error) {
  140. data, err := json.Marshal(container)
  141. if err != nil {
  142. return
  143. }
  144. err = ioutil.WriteFile(container.jsonPath(), data, 0666)
  145. if err != nil {
  146. return
  147. }
  148. return container.writeHostConfig()
  149. }
  150. func (container *Container) readHostConfig() error {
  151. container.hostConfig = &runconfig.HostConfig{}
  152. // If the hostconfig file does not exist, do not read it.
  153. // (We still have to initialize container.hostConfig,
  154. // but that's OK, since we just did that above.)
  155. _, err := os.Stat(container.hostConfigPath())
  156. if os.IsNotExist(err) {
  157. return nil
  158. }
  159. data, err := ioutil.ReadFile(container.hostConfigPath())
  160. if err != nil {
  161. return err
  162. }
  163. return json.Unmarshal(data, container.hostConfig)
  164. }
  165. func (container *Container) writeHostConfig() (err error) {
  166. data, err := json.Marshal(container.hostConfig)
  167. if err != nil {
  168. return
  169. }
  170. return ioutil.WriteFile(container.hostConfigPath(), data, 0666)
  171. }
  172. func (container *Container) generateEnvConfig(env []string) error {
  173. data, err := json.Marshal(env)
  174. if err != nil {
  175. return err
  176. }
  177. p, err := container.EnvConfigPath()
  178. if err != nil {
  179. return err
  180. }
  181. ioutil.WriteFile(p, data, 0600)
  182. return nil
  183. }
  184. func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error {
  185. var cStdout, cStderr io.ReadCloser
  186. var nJobs int
  187. errors := make(chan error, 3)
  188. if stdin != nil && container.Config.OpenStdin {
  189. nJobs += 1
  190. if cStdin, err := container.StdinPipe(); err != nil {
  191. errors <- err
  192. } else {
  193. go func() {
  194. utils.Debugf("attach: stdin: begin")
  195. defer utils.Debugf("attach: stdin: end")
  196. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  197. if container.Config.StdinOnce && !container.Config.Tty {
  198. defer cStdin.Close()
  199. } else {
  200. defer func() {
  201. if cStdout != nil {
  202. cStdout.Close()
  203. }
  204. if cStderr != nil {
  205. cStderr.Close()
  206. }
  207. }()
  208. }
  209. if container.Config.Tty {
  210. _, err = utils.CopyEscapable(cStdin, stdin)
  211. } else {
  212. _, err = io.Copy(cStdin, stdin)
  213. }
  214. if err == io.ErrClosedPipe {
  215. err = nil
  216. }
  217. if err != nil {
  218. utils.Errorf("attach: stdin: %s", err)
  219. }
  220. errors <- err
  221. }()
  222. }
  223. }
  224. if stdout != nil {
  225. nJobs += 1
  226. if p, err := container.StdoutPipe(); err != nil {
  227. errors <- err
  228. } else {
  229. cStdout = p
  230. go func() {
  231. utils.Debugf("attach: stdout: begin")
  232. defer utils.Debugf("attach: stdout: end")
  233. // If we are in StdinOnce mode, then close stdin
  234. if container.Config.StdinOnce && stdin != nil {
  235. defer stdin.Close()
  236. }
  237. if stdinCloser != nil {
  238. defer stdinCloser.Close()
  239. }
  240. _, err := io.Copy(stdout, cStdout)
  241. if err == io.ErrClosedPipe {
  242. err = nil
  243. }
  244. if err != nil {
  245. utils.Errorf("attach: stdout: %s", err)
  246. }
  247. errors <- err
  248. }()
  249. }
  250. } else {
  251. go func() {
  252. if stdinCloser != nil {
  253. defer stdinCloser.Close()
  254. }
  255. if cStdout, err := container.StdoutPipe(); err != nil {
  256. utils.Errorf("attach: stdout pipe: %s", err)
  257. } else {
  258. io.Copy(&utils.NopWriter{}, cStdout)
  259. }
  260. }()
  261. }
  262. if stderr != nil {
  263. nJobs += 1
  264. if p, err := container.StderrPipe(); err != nil {
  265. errors <- err
  266. } else {
  267. cStderr = p
  268. go func() {
  269. utils.Debugf("attach: stderr: begin")
  270. defer utils.Debugf("attach: stderr: end")
  271. // If we are in StdinOnce mode, then close stdin
  272. if container.Config.StdinOnce && stdin != nil {
  273. defer stdin.Close()
  274. }
  275. if stdinCloser != nil {
  276. defer stdinCloser.Close()
  277. }
  278. _, err := io.Copy(stderr, cStderr)
  279. if err == io.ErrClosedPipe {
  280. err = nil
  281. }
  282. if err != nil {
  283. utils.Errorf("attach: stderr: %s", err)
  284. }
  285. errors <- err
  286. }()
  287. }
  288. } else {
  289. go func() {
  290. if stdinCloser != nil {
  291. defer stdinCloser.Close()
  292. }
  293. if cStderr, err := container.StderrPipe(); err != nil {
  294. utils.Errorf("attach: stdout pipe: %s", err)
  295. } else {
  296. io.Copy(&utils.NopWriter{}, cStderr)
  297. }
  298. }()
  299. }
  300. return utils.Go(func() error {
  301. defer func() {
  302. if cStdout != nil {
  303. cStdout.Close()
  304. }
  305. if cStderr != nil {
  306. cStderr.Close()
  307. }
  308. }()
  309. // FIXME: how to clean up the stdin goroutine without the unwanted side effect
  310. // of closing the passed stdin? Add an intermediary io.Pipe?
  311. for i := 0; i < nJobs; i += 1 {
  312. utils.Debugf("attach: waiting for job %d/%d", i+1, nJobs)
  313. if err := <-errors; err != nil {
  314. utils.Errorf("attach: job %d returned error %s, aborting all jobs", i+1, err)
  315. return err
  316. }
  317. utils.Debugf("attach: job %d completed successfully", i+1)
  318. }
  319. utils.Debugf("attach: all jobs completed successfully")
  320. return nil
  321. })
  322. }
  323. func populateCommand(c *Container) {
  324. var (
  325. en *execdriver.Network
  326. driverConfig []string
  327. )
  328. if !c.Config.NetworkDisabled {
  329. network := c.NetworkSettings
  330. en = &execdriver.Network{
  331. Gateway: network.Gateway,
  332. Bridge: network.Bridge,
  333. IPAddress: network.IPAddress,
  334. IPPrefixLen: network.IPPrefixLen,
  335. Mtu: c.runtime.config.Mtu,
  336. }
  337. }
  338. if lxcConf := c.hostConfig.LxcConf; lxcConf != nil {
  339. for _, pair := range lxcConf {
  340. driverConfig = append(driverConfig, fmt.Sprintf("%s = %s", pair.Key, pair.Value))
  341. }
  342. }
  343. resources := &execdriver.Resources{
  344. Memory: c.Config.Memory,
  345. MemorySwap: c.Config.MemorySwap,
  346. CpuShares: c.Config.CpuShares,
  347. }
  348. c.command = &execdriver.Command{
  349. ID: c.ID,
  350. Privileged: c.hostConfig.Privileged,
  351. Rootfs: c.RootfsPath(),
  352. InitPath: "/.dockerinit",
  353. Entrypoint: c.Path,
  354. Arguments: c.Args,
  355. WorkingDir: c.Config.WorkingDir,
  356. Network: en,
  357. Tty: c.Config.Tty,
  358. User: c.Config.User,
  359. Config: driverConfig,
  360. Resources: resources,
  361. }
  362. c.command.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  363. }
  364. func (container *Container) Start() (err error) {
  365. container.Lock()
  366. defer container.Unlock()
  367. if container.State.IsRunning() {
  368. return fmt.Errorf("The container %s is already running.", container.ID)
  369. }
  370. defer func() {
  371. if err != nil {
  372. container.cleanup()
  373. }
  374. }()
  375. if err := container.Mount(); err != nil {
  376. return err
  377. }
  378. if container.runtime.config.DisableNetwork {
  379. container.Config.NetworkDisabled = true
  380. container.buildHostnameAndHostsFiles("127.0.1.1")
  381. } else {
  382. if err := container.allocateNetwork(); err != nil {
  383. return err
  384. }
  385. container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  386. }
  387. // Make sure the config is compatible with the current kernel
  388. if container.Config.Memory > 0 && !container.runtime.sysInfo.MemoryLimit {
  389. log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  390. container.Config.Memory = 0
  391. }
  392. if container.Config.Memory > 0 && !container.runtime.sysInfo.SwapLimit {
  393. log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  394. container.Config.MemorySwap = -1
  395. }
  396. if container.runtime.sysInfo.IPv4ForwardingDisabled {
  397. log.Printf("WARNING: IPv4 forwarding is disabled. Networking will not work")
  398. }
  399. if err := prepareVolumesForContainer(container); err != nil {
  400. return err
  401. }
  402. // Setup environment
  403. env := []string{
  404. "HOME=/",
  405. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  406. "HOSTNAME=" + container.Config.Hostname,
  407. }
  408. if container.Config.Tty {
  409. env = append(env, "TERM=xterm")
  410. }
  411. // Init any links between the parent and children
  412. runtime := container.runtime
  413. children, err := runtime.Children(container.Name)
  414. if err != nil {
  415. return err
  416. }
  417. if len(children) > 0 {
  418. container.activeLinks = make(map[string]*links.Link, len(children))
  419. // If we encounter an error make sure that we rollback any network
  420. // config and ip table changes
  421. rollback := func() {
  422. for _, link := range container.activeLinks {
  423. link.Disable()
  424. }
  425. container.activeLinks = nil
  426. }
  427. for linkAlias, child := range children {
  428. if !child.State.IsRunning() {
  429. return fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  430. }
  431. link, err := links.NewLink(
  432. container.NetworkSettings.IPAddress,
  433. child.NetworkSettings.IPAddress,
  434. linkAlias,
  435. child.Config.Env,
  436. child.Config.ExposedPorts,
  437. runtime.eng)
  438. if err != nil {
  439. rollback()
  440. return err
  441. }
  442. container.activeLinks[link.Alias()] = link
  443. if err := link.Enable(); err != nil {
  444. rollback()
  445. return err
  446. }
  447. for _, envVar := range link.ToEnv() {
  448. env = append(env, envVar)
  449. }
  450. }
  451. }
  452. for _, elem := range container.Config.Env {
  453. env = append(env, elem)
  454. }
  455. if err := container.generateEnvConfig(env); err != nil {
  456. return err
  457. }
  458. if container.Config.WorkingDir != "" {
  459. container.Config.WorkingDir = path.Clean(container.Config.WorkingDir)
  460. if err := os.MkdirAll(path.Join(container.basefs, container.Config.WorkingDir), 0755); err != nil {
  461. return nil
  462. }
  463. }
  464. envPath, err := container.EnvConfigPath()
  465. if err != nil {
  466. return err
  467. }
  468. if err := mountVolumesForContainer(container, envPath); err != nil {
  469. return err
  470. }
  471. populateCommand(container)
  472. // Setup logging of stdout and stderr to disk
  473. if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil {
  474. return err
  475. }
  476. if err := container.runtime.LogToDisk(container.stderr, container.logPath("json"), "stderr"); err != nil {
  477. return err
  478. }
  479. container.waitLock = make(chan struct{})
  480. callbackLock := make(chan struct{})
  481. callback := func(command *execdriver.Command) {
  482. container.State.SetRunning(command.Pid())
  483. if command.Tty {
  484. // The callback is called after the process Start()
  485. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlace
  486. // which we close here.
  487. if c, ok := command.Stdout.(io.Closer); ok {
  488. c.Close()
  489. }
  490. }
  491. if err := container.ToDisk(); err != nil {
  492. utils.Debugf("%s", err)
  493. }
  494. close(callbackLock)
  495. }
  496. // We use a callback here instead of a goroutine and an chan for
  497. // syncronization purposes
  498. cErr := utils.Go(func() error { return container.monitor(callback) })
  499. // Start should not return until the process is actually running
  500. select {
  501. case <-callbackLock:
  502. case err := <-cErr:
  503. return err
  504. }
  505. return nil
  506. }
  507. func (container *Container) Run() error {
  508. if err := container.Start(); err != nil {
  509. return err
  510. }
  511. container.Wait()
  512. return nil
  513. }
  514. func (container *Container) Output() (output []byte, err error) {
  515. pipe, err := container.StdoutPipe()
  516. if err != nil {
  517. return nil, err
  518. }
  519. defer pipe.Close()
  520. if err := container.Start(); err != nil {
  521. return nil, err
  522. }
  523. output, err = ioutil.ReadAll(pipe)
  524. container.Wait()
  525. return output, err
  526. }
  527. // Container.StdinPipe returns a WriteCloser which can be used to feed data
  528. // to the standard input of the container's active process.
  529. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser
  530. // which can be used to retrieve the standard output (and error) generated
  531. // by the container's active process. The output (and error) are actually
  532. // copied and delivered to all StdoutPipe and StderrPipe consumers, using
  533. // a kind of "broadcaster".
  534. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  535. return container.stdinPipe, nil
  536. }
  537. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  538. reader, writer := io.Pipe()
  539. container.stdout.AddWriter(writer, "")
  540. return utils.NewBufReader(reader), nil
  541. }
  542. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  543. reader, writer := io.Pipe()
  544. container.stderr.AddWriter(writer, "")
  545. return utils.NewBufReader(reader), nil
  546. }
  547. func (container *Container) buildHostnameAndHostsFiles(IP string) {
  548. container.HostnamePath = path.Join(container.root, "hostname")
  549. ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  550. hostsContent := []byte(`
  551. 127.0.0.1 localhost
  552. ::1 localhost ip6-localhost ip6-loopback
  553. fe00::0 ip6-localnet
  554. ff00::0 ip6-mcastprefix
  555. ff02::1 ip6-allnodes
  556. ff02::2 ip6-allrouters
  557. `)
  558. container.HostsPath = path.Join(container.root, "hosts")
  559. if container.Config.Domainname != "" {
  560. hostsContent = append([]byte(fmt.Sprintf("%s\t%s.%s %s\n", IP, container.Config.Hostname, container.Config.Domainname, container.Config.Hostname)), hostsContent...)
  561. } else if !container.Config.NetworkDisabled {
  562. hostsContent = append([]byte(fmt.Sprintf("%s\t%s\n", IP, container.Config.Hostname)), hostsContent...)
  563. }
  564. ioutil.WriteFile(container.HostsPath, hostsContent, 0644)
  565. }
  566. func (container *Container) allocateNetwork() error {
  567. if container.Config.NetworkDisabled {
  568. return nil
  569. }
  570. var (
  571. env *engine.Env
  572. err error
  573. eng = container.runtime.eng
  574. )
  575. if container.State.IsGhost() {
  576. if container.runtime.config.DisableNetwork {
  577. env = &engine.Env{}
  578. } else {
  579. currentIP := container.NetworkSettings.IPAddress
  580. job := eng.Job("allocate_interface", container.ID)
  581. if currentIP != "" {
  582. job.Setenv("RequestIP", currentIP)
  583. }
  584. env, err = job.Stdout.AddEnv()
  585. if err != nil {
  586. return err
  587. }
  588. if err := job.Run(); err != nil {
  589. return err
  590. }
  591. }
  592. } else {
  593. job := eng.Job("allocate_interface", container.ID)
  594. env, err = job.Stdout.AddEnv()
  595. if err != nil {
  596. return err
  597. }
  598. if err := job.Run(); err != nil {
  599. return err
  600. }
  601. }
  602. if container.Config.PortSpecs != nil {
  603. utils.Debugf("Migrating port mappings for container: %s", strings.Join(container.Config.PortSpecs, ", "))
  604. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  605. return err
  606. }
  607. container.Config.PortSpecs = nil
  608. if err := container.writeHostConfig(); err != nil {
  609. return err
  610. }
  611. }
  612. var (
  613. portSpecs = make(nat.PortSet)
  614. bindings = make(nat.PortMap)
  615. )
  616. if !container.State.IsGhost() {
  617. if container.Config.ExposedPorts != nil {
  618. portSpecs = container.Config.ExposedPorts
  619. }
  620. if container.hostConfig.PortBindings != nil {
  621. bindings = container.hostConfig.PortBindings
  622. }
  623. } else {
  624. if container.NetworkSettings.Ports != nil {
  625. for port, binding := range container.NetworkSettings.Ports {
  626. portSpecs[port] = struct{}{}
  627. bindings[port] = binding
  628. }
  629. }
  630. }
  631. container.NetworkSettings.PortMapping = nil
  632. for port := range portSpecs {
  633. binding := bindings[port]
  634. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  635. binding = append(binding, nat.PortBinding{})
  636. }
  637. for i := 0; i < len(binding); i++ {
  638. b := binding[i]
  639. portJob := eng.Job("allocate_port", container.ID)
  640. portJob.Setenv("HostIP", b.HostIp)
  641. portJob.Setenv("HostPort", b.HostPort)
  642. portJob.Setenv("Proto", port.Proto())
  643. portJob.Setenv("ContainerPort", port.Port())
  644. portEnv, err := portJob.Stdout.AddEnv()
  645. if err != nil {
  646. return err
  647. }
  648. if err := portJob.Run(); err != nil {
  649. eng.Job("release_interface", container.ID).Run()
  650. return err
  651. }
  652. b.HostIp = portEnv.Get("HostIP")
  653. b.HostPort = portEnv.Get("HostPort")
  654. binding[i] = b
  655. }
  656. bindings[port] = binding
  657. }
  658. container.writeHostConfig()
  659. container.NetworkSettings.Ports = bindings
  660. container.NetworkSettings.Bridge = env.Get("Bridge")
  661. container.NetworkSettings.IPAddress = env.Get("IP")
  662. container.NetworkSettings.IPPrefixLen = env.GetInt("IPPrefixLen")
  663. container.NetworkSettings.Gateway = env.Get("Gateway")
  664. return nil
  665. }
  666. func (container *Container) releaseNetwork() {
  667. if container.Config.NetworkDisabled {
  668. return
  669. }
  670. eng := container.runtime.eng
  671. eng.Job("release_interface", container.ID).Run()
  672. container.NetworkSettings = &NetworkSettings{}
  673. }
  674. func (container *Container) monitor(callback execdriver.StartCallback) error {
  675. var (
  676. err error
  677. exitCode int
  678. )
  679. if container.command == nil {
  680. // This happends when you have a GHOST container with lxc
  681. populateCommand(container)
  682. err = container.runtime.RestoreCommand(container)
  683. } else {
  684. pipes := execdriver.NewPipes(container.stdin, container.stdout, container.stderr, container.Config.OpenStdin)
  685. exitCode, err = container.runtime.Run(container, pipes, callback)
  686. }
  687. if err != nil {
  688. utils.Errorf("Error running container: %s", err)
  689. }
  690. // Cleanup
  691. container.cleanup()
  692. // Re-create a brand new stdin pipe once the container exited
  693. if container.Config.OpenStdin {
  694. container.stdin, container.stdinPipe = io.Pipe()
  695. }
  696. container.State.SetStopped(exitCode)
  697. if container.runtime != nil && container.runtime.srv != nil {
  698. container.runtime.srv.LogEvent("die", container.ID, container.runtime.repositories.ImageName(container.Image))
  699. }
  700. close(container.waitLock)
  701. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  702. // If another goroutine was waiting for Wait() to return before removing the container's root
  703. // from the filesystem... At this point it may already have done so.
  704. // This is because State.setStopped() has already been called, and has caused Wait()
  705. // to return.
  706. // FIXME: why are we serializing running state to disk in the first place?
  707. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
  708. container.ToDisk()
  709. return err
  710. }
  711. func (container *Container) cleanup() {
  712. container.releaseNetwork()
  713. // Disable all active links
  714. if container.activeLinks != nil {
  715. for _, link := range container.activeLinks {
  716. link.Disable()
  717. }
  718. }
  719. if container.Config.OpenStdin {
  720. if err := container.stdin.Close(); err != nil {
  721. utils.Errorf("%s: Error close stdin: %s", container.ID, err)
  722. }
  723. }
  724. if err := container.stdout.CloseWriters(); err != nil {
  725. utils.Errorf("%s: Error close stdout: %s", container.ID, err)
  726. }
  727. if err := container.stderr.CloseWriters(); err != nil {
  728. utils.Errorf("%s: Error close stderr: %s", container.ID, err)
  729. }
  730. if container.command.Terminal != nil {
  731. if err := container.command.Terminal.Close(); err != nil {
  732. utils.Errorf("%s: Error closing terminal: %s", container.ID, err)
  733. }
  734. }
  735. unmountVolumesForContainer(container)
  736. if err := container.Unmount(); err != nil {
  737. log.Printf("%v: Failed to umount filesystem: %v", container.ID, err)
  738. }
  739. }
  740. func (container *Container) kill(sig int) error {
  741. container.Lock()
  742. defer container.Unlock()
  743. if !container.State.IsRunning() {
  744. return nil
  745. }
  746. return container.runtime.Kill(container, sig)
  747. }
  748. func (container *Container) Kill() error {
  749. if !container.State.IsRunning() {
  750. return nil
  751. }
  752. // 1. Send SIGKILL
  753. if err := container.kill(9); err != nil {
  754. return err
  755. }
  756. // 2. Wait for the process to die, in last resort, try to kill the process directly
  757. if err := container.WaitTimeout(10 * time.Second); err != nil {
  758. if container.command == nil {
  759. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", utils.TruncateID(container.ID))
  760. }
  761. log.Printf("Container %s failed to exit within 10 seconds of lxc-kill %s - trying direct SIGKILL", "SIGKILL", utils.TruncateID(container.ID))
  762. if err := container.runtime.Kill(container, 9); err != nil {
  763. return err
  764. }
  765. }
  766. container.Wait()
  767. return nil
  768. }
  769. func (container *Container) Stop(seconds int) error {
  770. if !container.State.IsRunning() {
  771. return nil
  772. }
  773. // 1. Send a SIGTERM
  774. if err := container.kill(15); err != nil {
  775. utils.Debugf("Error sending kill SIGTERM: %s", err)
  776. log.Print("Failed to send SIGTERM to the process, force killing")
  777. if err := container.kill(9); err != nil {
  778. return err
  779. }
  780. }
  781. // 2. Wait for the process to exit on its own
  782. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  783. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  784. // 3. If it doesn't, then send SIGKILL
  785. if err := container.Kill(); err != nil {
  786. return err
  787. }
  788. }
  789. return nil
  790. }
  791. func (container *Container) Restart(seconds int) error {
  792. // Avoid unnecessarily unmounting and then directly mounting
  793. // the container when the container stops and then starts
  794. // again
  795. if err := container.Mount(); err == nil {
  796. defer container.Unmount()
  797. }
  798. if err := container.Stop(seconds); err != nil {
  799. return err
  800. }
  801. return container.Start()
  802. }
  803. // Wait blocks until the container stops running, then returns its exit code.
  804. func (container *Container) Wait() int {
  805. <-container.waitLock
  806. return container.State.GetExitCode()
  807. }
  808. func (container *Container) Resize(h, w int) error {
  809. return container.command.Terminal.Resize(h, w)
  810. }
  811. func (container *Container) ExportRw() (archive.Archive, error) {
  812. if err := container.Mount(); err != nil {
  813. return nil, err
  814. }
  815. if container.runtime == nil {
  816. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  817. }
  818. archive, err := container.runtime.Diff(container)
  819. if err != nil {
  820. container.Unmount()
  821. return nil, err
  822. }
  823. return utils.NewReadCloserWrapper(archive, func() error {
  824. err := archive.Close()
  825. container.Unmount()
  826. return err
  827. }), nil
  828. }
  829. func (container *Container) Export() (archive.Archive, error) {
  830. if err := container.Mount(); err != nil {
  831. return nil, err
  832. }
  833. archive, err := archive.Tar(container.basefs, archive.Uncompressed)
  834. if err != nil {
  835. container.Unmount()
  836. return nil, err
  837. }
  838. return utils.NewReadCloserWrapper(archive, func() error {
  839. err := archive.Close()
  840. container.Unmount()
  841. return err
  842. }), nil
  843. }
  844. func (container *Container) WaitTimeout(timeout time.Duration) error {
  845. done := make(chan bool)
  846. go func() {
  847. container.Wait()
  848. done <- true
  849. }()
  850. select {
  851. case <-time.After(timeout):
  852. return fmt.Errorf("Timed Out")
  853. case <-done:
  854. return nil
  855. }
  856. }
  857. func (container *Container) Mount() error {
  858. return container.runtime.Mount(container)
  859. }
  860. func (container *Container) Changes() ([]archive.Change, error) {
  861. return container.runtime.Changes(container)
  862. }
  863. func (container *Container) GetImage() (*Image, error) {
  864. if container.runtime == nil {
  865. return nil, fmt.Errorf("Can't get image of unregistered container")
  866. }
  867. return container.runtime.graph.Get(container.Image)
  868. }
  869. func (container *Container) Unmount() error {
  870. return container.runtime.Unmount(container)
  871. }
  872. func (container *Container) logPath(name string) string {
  873. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name))
  874. }
  875. func (container *Container) ReadLog(name string) (io.Reader, error) {
  876. return os.Open(container.logPath(name))
  877. }
  878. func (container *Container) hostConfigPath() string {
  879. return path.Join(container.root, "hostconfig.json")
  880. }
  881. func (container *Container) jsonPath() string {
  882. return path.Join(container.root, "config.json")
  883. }
  884. func (container *Container) EnvConfigPath() (string, error) {
  885. p := path.Join(container.root, "config.env")
  886. if _, err := os.Stat(p); err != nil {
  887. if os.IsNotExist(err) {
  888. f, err := os.Create(p)
  889. if err != nil {
  890. return "", err
  891. }
  892. f.Close()
  893. } else {
  894. return "", err
  895. }
  896. }
  897. return p, nil
  898. }
  899. // This method must be exported to be used from the lxc template
  900. // This directory is only usable when the container is running
  901. func (container *Container) RootfsPath() string {
  902. return path.Join(container.root, "root")
  903. }
  904. // This is the stand-alone version of the root fs, without any additional mounts.
  905. // This directory is usable whenever the container is mounted (and not unmounted)
  906. func (container *Container) BasefsPath() string {
  907. return container.basefs
  908. }
  909. func validateID(id string) error {
  910. if id == "" {
  911. return fmt.Errorf("Invalid empty id")
  912. }
  913. return nil
  914. }
  915. // GetSize, return real size, virtual size
  916. func (container *Container) GetSize() (int64, int64) {
  917. var (
  918. sizeRw, sizeRootfs int64
  919. err error
  920. driver = container.runtime.driver
  921. )
  922. if err := container.Mount(); err != nil {
  923. utils.Errorf("Warning: failed to compute size of container rootfs %s: %s", container.ID, err)
  924. return sizeRw, sizeRootfs
  925. }
  926. defer container.Unmount()
  927. if differ, ok := container.runtime.driver.(graphdriver.Differ); ok {
  928. sizeRw, err = differ.DiffSize(container.ID)
  929. if err != nil {
  930. utils.Errorf("Warning: driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  931. // FIXME: GetSize should return an error. Not changing it now in case
  932. // there is a side-effect.
  933. sizeRw = -1
  934. }
  935. } else {
  936. changes, _ := container.Changes()
  937. if changes != nil {
  938. sizeRw = archive.ChangesSize(container.basefs, changes)
  939. } else {
  940. sizeRw = -1
  941. }
  942. }
  943. if _, err = os.Stat(container.basefs); err != nil {
  944. if sizeRootfs, err = utils.TreeSize(container.basefs); err != nil {
  945. sizeRootfs = -1
  946. }
  947. }
  948. return sizeRw, sizeRootfs
  949. }
  950. func (container *Container) Copy(resource string) (io.ReadCloser, error) {
  951. if err := container.Mount(); err != nil {
  952. return nil, err
  953. }
  954. var filter []string
  955. basePath := path.Join(container.basefs, resource)
  956. stat, err := os.Stat(basePath)
  957. if err != nil {
  958. container.Unmount()
  959. return nil, err
  960. }
  961. if !stat.IsDir() {
  962. d, f := path.Split(basePath)
  963. basePath = d
  964. filter = []string{f}
  965. } else {
  966. filter = []string{path.Base(basePath)}
  967. basePath = path.Dir(basePath)
  968. }
  969. archive, err := archive.TarFilter(basePath, &archive.TarOptions{
  970. Compression: archive.Uncompressed,
  971. Includes: filter,
  972. })
  973. if err != nil {
  974. return nil, err
  975. }
  976. return utils.NewReadCloserWrapper(archive, func() error {
  977. err := archive.Close()
  978. container.Unmount()
  979. return err
  980. }), nil
  981. }
  982. // Returns true if the container exposes a certain port
  983. func (container *Container) Exposes(p nat.Port) bool {
  984. _, exists := container.Config.ExposedPorts[p]
  985. return exists
  986. }
  987. func (container *Container) GetPtyMaster() (*os.File, error) {
  988. ttyConsole, ok := container.command.Terminal.(*execdriver.TtyConsole)
  989. if !ok {
  990. return nil, ErrNoTTY
  991. }
  992. return ttyConsole.Master, nil
  993. }