container.go 31 KB

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