container.go 32 KB

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