container.go 30 KB

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