container.go 31 KB

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