container.go 30 KB

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