container.go 29 KB

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