container.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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/daemon/graphdriver"
  19. "github.com/docker/docker/engine"
  20. "github.com/docker/docker/image"
  21. "github.com/docker/docker/links"
  22. "github.com/docker/docker/nat"
  23. "github.com/docker/docker/pkg/broadcastwriter"
  24. "github.com/docker/docker/pkg/ioutils"
  25. "github.com/docker/docker/pkg/log"
  26. "github.com/docker/docker/pkg/networkfs/etchosts"
  27. "github.com/docker/docker/pkg/networkfs/resolvconf"
  28. "github.com/docker/docker/pkg/symlink"
  29. "github.com/docker/docker/runconfig"
  30. "github.com/docker/docker/utils"
  31. )
  32. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  33. var (
  34. ErrNotATTY = errors.New("The PTY is not a file")
  35. ErrNoTTY = errors.New("No PTY found")
  36. ErrContainerStart = errors.New("The container failed to start. Unknown error")
  37. ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.")
  38. )
  39. type StreamConfig struct {
  40. stdout *broadcastwriter.BroadcastWriter
  41. stderr *broadcastwriter.BroadcastWriter
  42. stdin io.ReadCloser
  43. stdinPipe io.WriteCloser
  44. }
  45. type Container struct {
  46. *State `json:"State"` // Needed for remote api version <= 1.11
  47. root string // Path to the "home" of the container, including metadata.
  48. basefs string // Path to the graphdriver mountpoint
  49. ID string
  50. Created time.Time
  51. Path string
  52. Args []string
  53. Config *runconfig.Config
  54. Image string
  55. NetworkSettings *NetworkSettings
  56. ResolvConfPath string
  57. HostnamePath string
  58. HostsPath string
  59. Name string
  60. Driver string
  61. ExecDriver string
  62. command *execdriver.Command
  63. StreamConfig
  64. daemon *Daemon
  65. MountLabel, ProcessLabel string
  66. RestartCount int
  67. Volumes map[string]string
  68. // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk.
  69. // Easier than migrating older container configs :)
  70. VolumesRW map[string]bool
  71. hostConfig *runconfig.HostConfig
  72. activeLinks map[string]*links.Link
  73. monitor *containerMonitor
  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. return etchosts.Build(container.HostsPath, IP, container.Config.Hostname, container.Config.Domainname, &extraContent)
  361. }
  362. func (container *Container) buildHostnameAndHostsFiles(IP string) error {
  363. if err := container.buildHostnameFile(); err != nil {
  364. return err
  365. }
  366. return container.buildHostsFiles(IP)
  367. }
  368. func (container *Container) allocateNetwork() error {
  369. mode := container.hostConfig.NetworkMode
  370. if container.Config.NetworkDisabled || !mode.IsPrivate() {
  371. return nil
  372. }
  373. var (
  374. env *engine.Env
  375. err error
  376. eng = container.daemon.eng
  377. )
  378. job := eng.Job("allocate_interface", container.ID)
  379. if env, err = job.Stdout.AddEnv(); err != nil {
  380. return err
  381. }
  382. if err := job.Run(); err != nil {
  383. return err
  384. }
  385. if container.Config.PortSpecs != nil {
  386. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  387. return err
  388. }
  389. container.Config.PortSpecs = nil
  390. if err := container.WriteHostConfig(); err != nil {
  391. return err
  392. }
  393. }
  394. var (
  395. portSpecs = make(nat.PortSet)
  396. bindings = make(nat.PortMap)
  397. )
  398. if container.Config.ExposedPorts != nil {
  399. portSpecs = container.Config.ExposedPorts
  400. }
  401. if container.hostConfig.PortBindings != nil {
  402. for p, b := range container.hostConfig.PortBindings {
  403. bindings[p] = []nat.PortBinding{}
  404. for _, bb := range b {
  405. bindings[p] = append(bindings[p], nat.PortBinding{
  406. HostIp: bb.HostIp,
  407. HostPort: bb.HostPort,
  408. })
  409. }
  410. }
  411. }
  412. container.NetworkSettings.PortMapping = nil
  413. for port := range portSpecs {
  414. if err := container.allocatePort(eng, port, bindings); err != nil {
  415. return err
  416. }
  417. }
  418. container.WriteHostConfig()
  419. container.NetworkSettings.Ports = bindings
  420. container.NetworkSettings.Bridge = env.Get("Bridge")
  421. container.NetworkSettings.IPAddress = env.Get("IP")
  422. container.NetworkSettings.IPPrefixLen = env.GetInt("IPPrefixLen")
  423. container.NetworkSettings.Gateway = env.Get("Gateway")
  424. return nil
  425. }
  426. func (container *Container) releaseNetwork() {
  427. if container.Config.NetworkDisabled {
  428. return
  429. }
  430. eng := container.daemon.eng
  431. eng.Job("release_interface", container.ID).Run()
  432. container.NetworkSettings = &NetworkSettings{}
  433. }
  434. // cleanup releases any network resources allocated to the container along with any rules
  435. // around how containers are linked together. It also unmounts the container's root filesystem.
  436. func (container *Container) cleanup() {
  437. container.releaseNetwork()
  438. // Disable all active links
  439. if container.activeLinks != nil {
  440. for _, link := range container.activeLinks {
  441. link.Disable()
  442. }
  443. }
  444. if err := container.Unmount(); err != nil {
  445. log.Errorf("%v: Failed to umount filesystem: %v", container.ID, err)
  446. }
  447. }
  448. func (container *Container) KillSig(sig int) error {
  449. log.Debugf("Sending %d to %s", sig, container.ID)
  450. container.Lock()
  451. defer container.Unlock()
  452. // We could unpause the container for them rather than returning this error
  453. if container.Paused {
  454. return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID)
  455. }
  456. if !container.Running {
  457. return nil
  458. }
  459. // signal to the monitor that it should not restart the container
  460. // after we send the kill signal
  461. container.monitor.ExitOnNext()
  462. // if the container is currently restarting we do not need to send the signal
  463. // to the process. Telling the monitor that it should exit on it's next event
  464. // loop is enough
  465. if container.Restarting {
  466. return nil
  467. }
  468. return container.daemon.Kill(container, sig)
  469. }
  470. func (container *Container) Pause() error {
  471. if container.IsPaused() {
  472. return fmt.Errorf("Container %s is already paused", container.ID)
  473. }
  474. if !container.IsRunning() {
  475. return fmt.Errorf("Container %s is not running", container.ID)
  476. }
  477. return container.daemon.Pause(container)
  478. }
  479. func (container *Container) Unpause() error {
  480. if !container.IsPaused() {
  481. return fmt.Errorf("Container %s is not paused", container.ID)
  482. }
  483. if !container.IsRunning() {
  484. return fmt.Errorf("Container %s is not running", container.ID)
  485. }
  486. return container.daemon.Unpause(container)
  487. }
  488. func (container *Container) Kill() error {
  489. if !container.IsRunning() {
  490. return nil
  491. }
  492. // 1. Send SIGKILL
  493. if err := container.KillSig(9); err != nil {
  494. return err
  495. }
  496. // 2. Wait for the process to die, in last resort, try to kill the process directly
  497. if _, err := container.WaitStop(10 * time.Second); err != nil {
  498. // Ensure that we don't kill ourselves
  499. if pid := container.GetPid(); pid != 0 {
  500. log.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", utils.TruncateID(container.ID))
  501. if err := syscall.Kill(pid, 9); err != nil {
  502. return err
  503. }
  504. }
  505. }
  506. container.WaitStop(-1 * time.Second)
  507. return nil
  508. }
  509. func (container *Container) Stop(seconds int) error {
  510. if !container.IsRunning() {
  511. return nil
  512. }
  513. // 1. Send a SIGTERM
  514. if err := container.KillSig(15); err != nil {
  515. log.Infof("Failed to send SIGTERM to the process, force killing")
  516. if err := container.KillSig(9); err != nil {
  517. return err
  518. }
  519. }
  520. // 2. Wait for the process to exit on its own
  521. if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil {
  522. log.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  523. // 3. If it doesn't, then send SIGKILL
  524. if err := container.Kill(); err != nil {
  525. container.WaitStop(-1 * time.Second)
  526. return err
  527. }
  528. }
  529. return nil
  530. }
  531. func (container *Container) Restart(seconds int) error {
  532. // Avoid unnecessarily unmounting and then directly mounting
  533. // the container when the container stops and then starts
  534. // again
  535. if err := container.Mount(); err == nil {
  536. defer container.Unmount()
  537. }
  538. if err := container.Stop(seconds); err != nil {
  539. return err
  540. }
  541. return container.Start()
  542. }
  543. func (container *Container) Resize(h, w int) error {
  544. return container.command.ProcessConfig.Terminal.Resize(h, w)
  545. }
  546. func (container *Container) ExportRw() (archive.Archive, error) {
  547. if err := container.Mount(); err != nil {
  548. return nil, err
  549. }
  550. if container.daemon == nil {
  551. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  552. }
  553. archive, err := container.daemon.Diff(container)
  554. if err != nil {
  555. container.Unmount()
  556. return nil, err
  557. }
  558. return ioutils.NewReadCloserWrapper(archive, func() error {
  559. err := archive.Close()
  560. container.Unmount()
  561. return err
  562. }),
  563. nil
  564. }
  565. func (container *Container) Export() (archive.Archive, error) {
  566. if err := container.Mount(); err != nil {
  567. return nil, err
  568. }
  569. archive, err := archive.Tar(container.basefs, archive.Uncompressed)
  570. if err != nil {
  571. container.Unmount()
  572. return nil, err
  573. }
  574. return ioutils.NewReadCloserWrapper(archive, func() error {
  575. err := archive.Close()
  576. container.Unmount()
  577. return err
  578. }),
  579. nil
  580. }
  581. func (container *Container) Mount() error {
  582. return container.daemon.Mount(container)
  583. }
  584. func (container *Container) changes() ([]archive.Change, error) {
  585. return container.daemon.Changes(container)
  586. }
  587. func (container *Container) Changes() ([]archive.Change, error) {
  588. container.Lock()
  589. defer container.Unlock()
  590. return container.changes()
  591. }
  592. func (container *Container) GetImage() (*image.Image, error) {
  593. if container.daemon == nil {
  594. return nil, fmt.Errorf("Can't get image of unregistered container")
  595. }
  596. return container.daemon.graph.Get(container.Image)
  597. }
  598. func (container *Container) Unmount() error {
  599. return container.daemon.Unmount(container)
  600. }
  601. func (container *Container) logPath(name string) (string, error) {
  602. return container.getRootResourcePath(fmt.Sprintf("%s-%s.log", container.ID, name))
  603. }
  604. func (container *Container) ReadLog(name string) (io.Reader, error) {
  605. pth, err := container.logPath(name)
  606. if err != nil {
  607. return nil, err
  608. }
  609. return os.Open(pth)
  610. }
  611. func (container *Container) hostConfigPath() (string, error) {
  612. return container.getRootResourcePath("hostconfig.json")
  613. }
  614. func (container *Container) jsonPath() (string, error) {
  615. return container.getRootResourcePath("config.json")
  616. }
  617. // This method must be exported to be used from the lxc template
  618. // This directory is only usable when the container is running
  619. func (container *Container) RootfsPath() string {
  620. return container.basefs
  621. }
  622. func validateID(id string) error {
  623. if id == "" {
  624. return fmt.Errorf("Invalid empty id")
  625. }
  626. return nil
  627. }
  628. // GetSize, return real size, virtual size
  629. func (container *Container) GetSize() (int64, int64) {
  630. var (
  631. sizeRw, sizeRootfs int64
  632. err error
  633. driver = container.daemon.driver
  634. )
  635. if err := container.Mount(); err != nil {
  636. log.Errorf("Warning: failed to compute size of container rootfs %s: %s", container.ID, err)
  637. return sizeRw, sizeRootfs
  638. }
  639. defer container.Unmount()
  640. if differ, ok := driver.(graphdriver.Differ); ok {
  641. sizeRw, err = differ.DiffSize(container.ID)
  642. if err != nil {
  643. log.Errorf("Warning: driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  644. // FIXME: GetSize should return an error. Not changing it now in case
  645. // there is a side-effect.
  646. sizeRw = -1
  647. }
  648. } else {
  649. changes, _ := container.changes()
  650. if changes != nil {
  651. sizeRw = archive.ChangesSize(container.basefs, changes)
  652. } else {
  653. sizeRw = -1
  654. }
  655. }
  656. if _, err = os.Stat(container.basefs); err != nil {
  657. if sizeRootfs, err = utils.TreeSize(container.basefs); err != nil {
  658. sizeRootfs = -1
  659. }
  660. }
  661. return sizeRw, sizeRootfs
  662. }
  663. func (container *Container) Copy(resource string) (io.ReadCloser, error) {
  664. if err := container.Mount(); err != nil {
  665. return nil, err
  666. }
  667. var filter []string
  668. basePath, err := container.getResourcePath(resource)
  669. if err != nil {
  670. container.Unmount()
  671. return nil, err
  672. }
  673. stat, err := os.Stat(basePath)
  674. if err != nil {
  675. container.Unmount()
  676. return nil, err
  677. }
  678. if !stat.IsDir() {
  679. d, f := path.Split(basePath)
  680. basePath = d
  681. filter = []string{f}
  682. } else {
  683. filter = []string{path.Base(basePath)}
  684. basePath = path.Dir(basePath)
  685. }
  686. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  687. Compression: archive.Uncompressed,
  688. Includes: filter,
  689. })
  690. if err != nil {
  691. container.Unmount()
  692. return nil, err
  693. }
  694. return ioutils.NewReadCloserWrapper(archive, func() error {
  695. err := archive.Close()
  696. container.Unmount()
  697. return err
  698. }),
  699. nil
  700. }
  701. // Returns true if the container exposes a certain port
  702. func (container *Container) Exposes(p nat.Port) bool {
  703. _, exists := container.Config.ExposedPorts[p]
  704. return exists
  705. }
  706. func (container *Container) GetPtyMaster() (*os.File, error) {
  707. ttyConsole, ok := container.command.ProcessConfig.Terminal.(execdriver.TtyTerminal)
  708. if !ok {
  709. return nil, ErrNoTTY
  710. }
  711. return ttyConsole.Master(), nil
  712. }
  713. func (container *Container) HostConfig() *runconfig.HostConfig {
  714. container.Lock()
  715. res := container.hostConfig
  716. container.Unlock()
  717. return res
  718. }
  719. func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) {
  720. container.Lock()
  721. container.hostConfig = hostConfig
  722. container.Unlock()
  723. }
  724. func (container *Container) DisableLink(name string) {
  725. if container.activeLinks != nil {
  726. if link, exists := container.activeLinks[name]; exists {
  727. link.Disable()
  728. } else {
  729. log.Debugf("Could not find active link for %s", name)
  730. }
  731. }
  732. }
  733. func (container *Container) setupContainerDns() error {
  734. if container.ResolvConfPath != "" {
  735. return nil
  736. }
  737. var (
  738. config = container.hostConfig
  739. daemon = container.daemon
  740. )
  741. resolvConf, err := resolvconf.Get()
  742. if err != nil {
  743. return err
  744. }
  745. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  746. if err != nil {
  747. return err
  748. }
  749. if config.NetworkMode != "host" && (len(config.Dns) > 0 || len(daemon.config.Dns) > 0 || len(config.DnsSearch) > 0 || len(daemon.config.DnsSearch) > 0) {
  750. var (
  751. dns = resolvconf.GetNameservers(resolvConf)
  752. dnsSearch = resolvconf.GetSearchDomains(resolvConf)
  753. )
  754. if len(config.Dns) > 0 {
  755. dns = config.Dns
  756. } else if len(daemon.config.Dns) > 0 {
  757. dns = daemon.config.Dns
  758. }
  759. if len(config.DnsSearch) > 0 {
  760. dnsSearch = config.DnsSearch
  761. } else if len(daemon.config.DnsSearch) > 0 {
  762. dnsSearch = daemon.config.DnsSearch
  763. }
  764. return resolvconf.Build(container.ResolvConfPath, dns, dnsSearch)
  765. }
  766. return ioutil.WriteFile(container.ResolvConfPath, resolvConf, 0644)
  767. }
  768. func (container *Container) updateParentsHosts() error {
  769. parents, err := container.daemon.Parents(container.Name)
  770. if err != nil {
  771. return err
  772. }
  773. for _, cid := range parents {
  774. if cid == "0" {
  775. continue
  776. }
  777. c := container.daemon.Get(cid)
  778. if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() {
  779. if err := etchosts.Update(c.HostsPath, container.NetworkSettings.IPAddress, container.Name[1:]); err != nil {
  780. return fmt.Errorf("Failed to update /etc/hosts in parent container: %v", err)
  781. }
  782. }
  783. }
  784. return nil
  785. }
  786. func (container *Container) initializeNetworking() error {
  787. var err error
  788. if container.hostConfig.NetworkMode.IsHost() {
  789. container.Config.Hostname, err = os.Hostname()
  790. if err != nil {
  791. return err
  792. }
  793. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  794. if len(parts) > 1 {
  795. container.Config.Hostname = parts[0]
  796. container.Config.Domainname = parts[1]
  797. }
  798. content, err := ioutil.ReadFile("/etc/hosts")
  799. if os.IsNotExist(err) {
  800. return container.buildHostnameAndHostsFiles("")
  801. } else if err != nil {
  802. return err
  803. }
  804. if err := container.buildHostnameFile(); err != nil {
  805. return err
  806. }
  807. hostsPath, err := container.getRootResourcePath("hosts")
  808. if err != nil {
  809. return err
  810. }
  811. container.HostsPath = hostsPath
  812. return ioutil.WriteFile(container.HostsPath, content, 0644)
  813. }
  814. if container.hostConfig.NetworkMode.IsContainer() {
  815. // we need to get the hosts files from the container to join
  816. nc, err := container.getNetworkedContainer()
  817. if err != nil {
  818. return err
  819. }
  820. container.HostsPath = nc.HostsPath
  821. container.ResolvConfPath = nc.ResolvConfPath
  822. container.Config.Hostname = nc.Config.Hostname
  823. container.Config.Domainname = nc.Config.Domainname
  824. return nil
  825. }
  826. if container.daemon.config.DisableNetwork {
  827. container.Config.NetworkDisabled = true
  828. return container.buildHostnameAndHostsFiles("127.0.1.1")
  829. }
  830. if err := container.allocateNetwork(); err != nil {
  831. return err
  832. }
  833. return container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  834. }
  835. // Make sure the config is compatible with the current kernel
  836. func (container *Container) verifyDaemonSettings() {
  837. if container.Config.Memory > 0 && !container.daemon.sysInfo.MemoryLimit {
  838. log.Infof("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.")
  839. container.Config.Memory = 0
  840. }
  841. if container.Config.Memory > 0 && !container.daemon.sysInfo.SwapLimit {
  842. log.Infof("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.")
  843. container.Config.MemorySwap = -1
  844. }
  845. if container.daemon.sysInfo.IPv4ForwardingDisabled {
  846. log.Infof("WARNING: IPv4 forwarding is disabled. Networking will not work")
  847. }
  848. }
  849. func (container *Container) setupLinkedContainers() ([]string, error) {
  850. var (
  851. env []string
  852. daemon = container.daemon
  853. )
  854. children, err := daemon.Children(container.Name)
  855. if err != nil {
  856. return nil, err
  857. }
  858. if len(children) > 0 {
  859. container.activeLinks = make(map[string]*links.Link, len(children))
  860. // If we encounter an error make sure that we rollback any network
  861. // config and ip table changes
  862. rollback := func() {
  863. for _, link := range container.activeLinks {
  864. link.Disable()
  865. }
  866. container.activeLinks = nil
  867. }
  868. for linkAlias, child := range children {
  869. if !child.IsRunning() {
  870. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  871. }
  872. link, err := links.NewLink(
  873. container.NetworkSettings.IPAddress,
  874. child.NetworkSettings.IPAddress,
  875. linkAlias,
  876. child.Config.Env,
  877. child.Config.ExposedPorts,
  878. daemon.eng)
  879. if err != nil {
  880. rollback()
  881. return nil, err
  882. }
  883. container.activeLinks[link.Alias()] = link
  884. if err := link.Enable(); err != nil {
  885. rollback()
  886. return nil, err
  887. }
  888. for _, envVar := range link.ToEnv() {
  889. env = append(env, envVar)
  890. }
  891. }
  892. }
  893. return env, nil
  894. }
  895. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  896. // Setup environment
  897. env := []string{
  898. "PATH=" + DefaultPathEnv,
  899. "HOSTNAME=" + container.Config.Hostname,
  900. // Note: we don't set HOME here because it'll get autoset intelligently
  901. // based on the value of USER inside dockerinit, but only if it isn't
  902. // set already (ie, that can be overridden by setting HOME via -e or ENV
  903. // in a Dockerfile).
  904. }
  905. if container.Config.Tty {
  906. env = append(env, "TERM=xterm")
  907. }
  908. env = append(env, linkedEnv...)
  909. // because the env on the container can override certain default values
  910. // we need to replace the 'env' keys where they match and append anything
  911. // else.
  912. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  913. return env
  914. }
  915. func (container *Container) setupWorkingDirectory() error {
  916. if container.Config.WorkingDir != "" {
  917. container.Config.WorkingDir = path.Clean(container.Config.WorkingDir)
  918. pth, err := container.getResourcePath(container.Config.WorkingDir)
  919. if err != nil {
  920. return err
  921. }
  922. pthInfo, err := os.Stat(pth)
  923. if err != nil {
  924. if !os.IsNotExist(err) {
  925. return err
  926. }
  927. if err := os.MkdirAll(pth, 0755); err != nil {
  928. return err
  929. }
  930. }
  931. if pthInfo != nil && !pthInfo.IsDir() {
  932. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  933. }
  934. }
  935. return nil
  936. }
  937. func (container *Container) startLoggingToDisk() error {
  938. // Setup logging of stdout and stderr to disk
  939. pth, err := container.logPath("json")
  940. if err != nil {
  941. return err
  942. }
  943. if err := container.daemon.LogToDisk(container.stdout, pth, "stdout"); err != nil {
  944. return err
  945. }
  946. if err := container.daemon.LogToDisk(container.stderr, pth, "stderr"); err != nil {
  947. return err
  948. }
  949. return nil
  950. }
  951. func (container *Container) waitForStart() error {
  952. container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy)
  953. // block until we either receive an error from the initial start of the container's
  954. // process or until the process is running in the container
  955. select {
  956. case <-container.monitor.startSignal:
  957. case err := <-utils.Go(container.monitor.Start):
  958. return err
  959. }
  960. return nil
  961. }
  962. func (container *Container) allocatePort(eng *engine.Engine, port nat.Port, bindings nat.PortMap) error {
  963. binding := bindings[port]
  964. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  965. binding = append(binding, nat.PortBinding{})
  966. }
  967. for i := 0; i < len(binding); i++ {
  968. b := binding[i]
  969. job := eng.Job("allocate_port", container.ID)
  970. job.Setenv("HostIP", b.HostIp)
  971. job.Setenv("HostPort", b.HostPort)
  972. job.Setenv("Proto", port.Proto())
  973. job.Setenv("ContainerPort", port.Port())
  974. portEnv, err := job.Stdout.AddEnv()
  975. if err != nil {
  976. return err
  977. }
  978. if err := job.Run(); err != nil {
  979. eng.Job("release_interface", container.ID).Run()
  980. return err
  981. }
  982. b.HostIp = portEnv.Get("HostIP")
  983. b.HostPort = portEnv.Get("HostPort")
  984. binding[i] = b
  985. }
  986. bindings[port] = binding
  987. return nil
  988. }
  989. func (container *Container) GetProcessLabel() string {
  990. // even if we have a process label return "" if we are running
  991. // in privileged mode
  992. if container.hostConfig.Privileged {
  993. return ""
  994. }
  995. return container.ProcessLabel
  996. }
  997. func (container *Container) GetMountLabel() string {
  998. if container.hostConfig.Privileged {
  999. return ""
  1000. }
  1001. return container.MountLabel
  1002. }
  1003. func (container *Container) getNetworkedContainer() (*Container, error) {
  1004. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  1005. switch parts[0] {
  1006. case "container":
  1007. nc := container.daemon.Get(parts[1])
  1008. if nc == nil {
  1009. return nil, fmt.Errorf("no such container to join network: %s", parts[1])
  1010. }
  1011. if !nc.IsRunning() {
  1012. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  1013. }
  1014. return nc, nil
  1015. default:
  1016. return nil, fmt.Errorf("network mode not set to container")
  1017. }
  1018. }
  1019. func (container *Container) GetVolumes() (map[string]*Volume, error) {
  1020. // Get all the bind-mounts
  1021. volumes, err := container.getBindMap()
  1022. if err != nil {
  1023. return nil, err
  1024. }
  1025. // Get all the normal volumes
  1026. for volPath, hostPath := range container.Volumes {
  1027. if _, exists := volumes[volPath]; exists {
  1028. continue
  1029. }
  1030. volumes[volPath] = &Volume{VolPath: volPath, HostPath: hostPath, isReadWrite: container.VolumesRW[volPath]}
  1031. }
  1032. return volumes, nil
  1033. }
  1034. func (container *Container) getBindMap() (map[string]*Volume, error) {
  1035. var (
  1036. // Create the requested bind mounts
  1037. volumes = map[string]*Volume{}
  1038. // Define illegal container destinations
  1039. illegalDsts = []string{"/", "."}
  1040. )
  1041. for _, bind := range container.hostConfig.Binds {
  1042. vol, err := parseBindVolumeSpec(bind)
  1043. if err != nil {
  1044. return nil, err
  1045. }
  1046. vol.isBindMount = true
  1047. // Bail if trying to mount to an illegal destination
  1048. for _, illegal := range illegalDsts {
  1049. if vol.VolPath == illegal {
  1050. return nil, fmt.Errorf("Illegal bind destination: %s", vol.VolPath)
  1051. }
  1052. }
  1053. volumes[filepath.Clean(vol.VolPath)] = &vol
  1054. }
  1055. return volumes, nil
  1056. }