container.go 30 KB

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