container.go 30 KB

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