container.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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
  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.IsContainer() || mode.IsHost() || mode.IsNone() {
  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. container.Lock()
  586. defer container.Unlock()
  587. return container.daemon.Changes(container)
  588. }
  589. func (container *Container) GetImage() (*image.Image, error) {
  590. if container.daemon == nil {
  591. return nil, fmt.Errorf("Can't get image of unregistered container")
  592. }
  593. return container.daemon.graph.Get(container.Image)
  594. }
  595. func (container *Container) Unmount() error {
  596. return container.daemon.Unmount(container)
  597. }
  598. func (container *Container) logPath(name string) (string, error) {
  599. return container.getRootResourcePath(fmt.Sprintf("%s-%s.log", container.ID, name))
  600. }
  601. func (container *Container) ReadLog(name string) (io.Reader, error) {
  602. pth, err := container.logPath(name)
  603. if err != nil {
  604. return nil, err
  605. }
  606. return os.Open(pth)
  607. }
  608. func (container *Container) hostConfigPath() (string, error) {
  609. return container.getRootResourcePath("hostconfig.json")
  610. }
  611. func (container *Container) jsonPath() (string, error) {
  612. return container.getRootResourcePath("config.json")
  613. }
  614. // This method must be exported to be used from the lxc template
  615. // This directory is only usable when the container is running
  616. func (container *Container) RootfsPath() string {
  617. return container.basefs
  618. }
  619. func validateID(id string) error {
  620. if id == "" {
  621. return fmt.Errorf("Invalid empty id")
  622. }
  623. return nil
  624. }
  625. // GetSize, return real size, virtual size
  626. func (container *Container) GetSize() (int64, int64) {
  627. var (
  628. sizeRw, sizeRootfs int64
  629. err error
  630. driver = container.daemon.driver
  631. )
  632. if err := container.Mount(); err != nil {
  633. log.Errorf("Warning: failed to compute size of container rootfs %s: %s", container.ID, err)
  634. return sizeRw, sizeRootfs
  635. }
  636. defer container.Unmount()
  637. if differ, ok := container.daemon.driver.(graphdriver.Differ); ok {
  638. sizeRw, err = differ.DiffSize(container.ID)
  639. if err != nil {
  640. log.Errorf("Warning: driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  641. // FIXME: GetSize should return an error. Not changing it now in case
  642. // there is a side-effect.
  643. sizeRw = -1
  644. }
  645. } else {
  646. changes, _ := container.Changes()
  647. if changes != nil {
  648. sizeRw = archive.ChangesSize(container.basefs, changes)
  649. } else {
  650. sizeRw = -1
  651. }
  652. }
  653. if _, err = os.Stat(container.basefs); err != nil {
  654. if sizeRootfs, err = utils.TreeSize(container.basefs); err != nil {
  655. sizeRootfs = -1
  656. }
  657. }
  658. return sizeRw, sizeRootfs
  659. }
  660. func (container *Container) Copy(resource string) (io.ReadCloser, error) {
  661. if err := container.Mount(); err != nil {
  662. return nil, err
  663. }
  664. var filter []string
  665. basePath, err := container.getResourcePath(resource)
  666. if err != nil {
  667. container.Unmount()
  668. return nil, err
  669. }
  670. stat, err := os.Stat(basePath)
  671. if err != nil {
  672. container.Unmount()
  673. return nil, err
  674. }
  675. if !stat.IsDir() {
  676. d, f := path.Split(basePath)
  677. basePath = d
  678. filter = []string{f}
  679. } else {
  680. filter = []string{path.Base(basePath)}
  681. basePath = path.Dir(basePath)
  682. }
  683. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  684. Compression: archive.Uncompressed,
  685. Includes: filter,
  686. })
  687. if err != nil {
  688. container.Unmount()
  689. return nil, err
  690. }
  691. return ioutils.NewReadCloserWrapper(archive, func() error {
  692. err := archive.Close()
  693. container.Unmount()
  694. return err
  695. }),
  696. nil
  697. }
  698. // Returns true if the container exposes a certain port
  699. func (container *Container) Exposes(p nat.Port) bool {
  700. _, exists := container.Config.ExposedPorts[p]
  701. return exists
  702. }
  703. func (container *Container) GetPtyMaster() (*os.File, error) {
  704. ttyConsole, ok := container.command.ProcessConfig.Terminal.(execdriver.TtyTerminal)
  705. if !ok {
  706. return nil, ErrNoTTY
  707. }
  708. return ttyConsole.Master(), nil
  709. }
  710. func (container *Container) HostConfig() *runconfig.HostConfig {
  711. container.Lock()
  712. res := container.hostConfig
  713. container.Unlock()
  714. return res
  715. }
  716. func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) {
  717. container.Lock()
  718. container.hostConfig = hostConfig
  719. container.Unlock()
  720. }
  721. func (container *Container) DisableLink(name string) {
  722. if container.activeLinks != nil {
  723. if link, exists := container.activeLinks[name]; exists {
  724. link.Disable()
  725. } else {
  726. log.Debugf("Could not find active link for %s", name)
  727. }
  728. }
  729. }
  730. func (container *Container) setupContainerDns() error {
  731. if container.ResolvConfPath != "" {
  732. return nil
  733. }
  734. var (
  735. config = container.hostConfig
  736. daemon = container.daemon
  737. )
  738. resolvConf, err := resolvconf.Get()
  739. if err != nil {
  740. return err
  741. }
  742. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  743. if err != nil {
  744. return err
  745. }
  746. if config.NetworkMode != "host" && (len(config.Dns) > 0 || len(daemon.config.Dns) > 0 || len(config.DnsSearch) > 0 || len(daemon.config.DnsSearch) > 0) {
  747. var (
  748. dns = resolvconf.GetNameservers(resolvConf)
  749. dnsSearch = resolvconf.GetSearchDomains(resolvConf)
  750. )
  751. if len(config.Dns) > 0 {
  752. dns = config.Dns
  753. } else if len(daemon.config.Dns) > 0 {
  754. dns = daemon.config.Dns
  755. }
  756. if len(config.DnsSearch) > 0 {
  757. dnsSearch = config.DnsSearch
  758. } else if len(daemon.config.DnsSearch) > 0 {
  759. dnsSearch = daemon.config.DnsSearch
  760. }
  761. return resolvconf.Build(container.ResolvConfPath, dns, dnsSearch)
  762. }
  763. return ioutil.WriteFile(container.ResolvConfPath, resolvConf, 0644)
  764. }
  765. func (container *Container) updateParentsHosts() error {
  766. parents, err := container.daemon.Parents(container.Name)
  767. if err != nil {
  768. return err
  769. }
  770. for _, cid := range parents {
  771. if cid == "0" {
  772. continue
  773. }
  774. c := container.daemon.Get(cid)
  775. if c != nil && !container.daemon.config.DisableNetwork && !container.hostConfig.NetworkMode.IsContainer() && !container.hostConfig.NetworkMode.IsHost() {
  776. if err := etchosts.Update(c.HostsPath, container.NetworkSettings.IPAddress, container.Name[1:]); err != nil {
  777. return fmt.Errorf("Failed to update /etc/hosts in parent container: %v", err)
  778. }
  779. }
  780. }
  781. return nil
  782. }
  783. func (container *Container) initializeNetworking() error {
  784. var err error
  785. if container.hostConfig.NetworkMode.IsHost() {
  786. container.Config.Hostname, err = os.Hostname()
  787. if err != nil {
  788. return err
  789. }
  790. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  791. if len(parts) > 1 {
  792. container.Config.Hostname = parts[0]
  793. container.Config.Domainname = parts[1]
  794. }
  795. content, err := ioutil.ReadFile("/etc/hosts")
  796. if os.IsNotExist(err) {
  797. return container.buildHostnameAndHostsFiles("")
  798. } else if err != nil {
  799. return err
  800. }
  801. if err := container.buildHostnameFile(); err != nil {
  802. return err
  803. }
  804. hostsPath, err := container.getRootResourcePath("hosts")
  805. if err != nil {
  806. return err
  807. }
  808. container.HostsPath = hostsPath
  809. return ioutil.WriteFile(container.HostsPath, content, 0644)
  810. }
  811. if container.hostConfig.NetworkMode.IsContainer() {
  812. // we need to get the hosts files from the container to join
  813. nc, err := container.getNetworkedContainer()
  814. if err != nil {
  815. return err
  816. }
  817. container.HostsPath = nc.HostsPath
  818. container.ResolvConfPath = nc.ResolvConfPath
  819. container.Config.Hostname = nc.Config.Hostname
  820. container.Config.Domainname = nc.Config.Domainname
  821. return nil
  822. }
  823. if container.daemon.config.DisableNetwork {
  824. container.Config.NetworkDisabled = true
  825. return container.buildHostnameAndHostsFiles("127.0.1.1")
  826. }
  827. if err := container.allocateNetwork(); err != nil {
  828. return err
  829. }
  830. return container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  831. }
  832. // Make sure the config is compatible with the current kernel
  833. func (container *Container) verifyDaemonSettings() {
  834. if container.Config.Memory > 0 && !container.daemon.sysInfo.MemoryLimit {
  835. log.Infof("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.")
  836. container.Config.Memory = 0
  837. }
  838. if container.Config.Memory > 0 && !container.daemon.sysInfo.SwapLimit {
  839. log.Infof("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.")
  840. container.Config.MemorySwap = -1
  841. }
  842. if container.daemon.sysInfo.IPv4ForwardingDisabled {
  843. log.Infof("WARNING: IPv4 forwarding is disabled. Networking will not work")
  844. }
  845. }
  846. func (container *Container) setupLinkedContainers() ([]string, error) {
  847. var (
  848. env []string
  849. daemon = container.daemon
  850. )
  851. children, err := daemon.Children(container.Name)
  852. if err != nil {
  853. return nil, err
  854. }
  855. if len(children) > 0 {
  856. container.activeLinks = make(map[string]*links.Link, len(children))
  857. // If we encounter an error make sure that we rollback any network
  858. // config and ip table changes
  859. rollback := func() {
  860. for _, link := range container.activeLinks {
  861. link.Disable()
  862. }
  863. container.activeLinks = nil
  864. }
  865. for linkAlias, child := range children {
  866. if !child.IsRunning() {
  867. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  868. }
  869. link, err := links.NewLink(
  870. container.NetworkSettings.IPAddress,
  871. child.NetworkSettings.IPAddress,
  872. linkAlias,
  873. child.Config.Env,
  874. child.Config.ExposedPorts,
  875. daemon.eng)
  876. if err != nil {
  877. rollback()
  878. return nil, err
  879. }
  880. container.activeLinks[link.Alias()] = link
  881. if err := link.Enable(); err != nil {
  882. rollback()
  883. return nil, err
  884. }
  885. for _, envVar := range link.ToEnv() {
  886. env = append(env, envVar)
  887. }
  888. }
  889. }
  890. return env, nil
  891. }
  892. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  893. // Setup environment
  894. env := []string{
  895. "PATH=" + DefaultPathEnv,
  896. "HOSTNAME=" + container.Config.Hostname,
  897. // Note: we don't set HOME here because it'll get autoset intelligently
  898. // based on the value of USER inside dockerinit, but only if it isn't
  899. // set already (ie, that can be overridden by setting HOME via -e or ENV
  900. // in a Dockerfile).
  901. }
  902. if container.Config.Tty {
  903. env = append(env, "TERM=xterm")
  904. }
  905. env = append(env, linkedEnv...)
  906. // because the env on the container can override certain default values
  907. // we need to replace the 'env' keys where they match and append anything
  908. // else.
  909. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  910. return env
  911. }
  912. func (container *Container) setupWorkingDirectory() error {
  913. if container.Config.WorkingDir != "" {
  914. container.Config.WorkingDir = path.Clean(container.Config.WorkingDir)
  915. pth, err := container.getResourcePath(container.Config.WorkingDir)
  916. if err != nil {
  917. return err
  918. }
  919. pthInfo, err := os.Stat(pth)
  920. if err != nil {
  921. if !os.IsNotExist(err) {
  922. return err
  923. }
  924. if err := os.MkdirAll(pth, 0755); err != nil {
  925. return err
  926. }
  927. }
  928. if pthInfo != nil && !pthInfo.IsDir() {
  929. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  930. }
  931. }
  932. return nil
  933. }
  934. func (container *Container) startLoggingToDisk() error {
  935. // Setup logging of stdout and stderr to disk
  936. pth, err := container.logPath("json")
  937. if err != nil {
  938. return err
  939. }
  940. if err := container.daemon.LogToDisk(container.stdout, pth, "stdout"); err != nil {
  941. return err
  942. }
  943. if err := container.daemon.LogToDisk(container.stderr, pth, "stderr"); err != nil {
  944. return err
  945. }
  946. return nil
  947. }
  948. func (container *Container) waitForStart() error {
  949. container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy)
  950. // block until we either receive an error from the initial start of the container's
  951. // process or until the process is running in the container
  952. select {
  953. case <-container.monitor.startSignal:
  954. case err := <-utils.Go(container.monitor.Start):
  955. return err
  956. }
  957. return nil
  958. }
  959. func (container *Container) allocatePort(eng *engine.Engine, port nat.Port, bindings nat.PortMap) error {
  960. binding := bindings[port]
  961. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  962. binding = append(binding, nat.PortBinding{})
  963. }
  964. for i := 0; i < len(binding); i++ {
  965. b := binding[i]
  966. job := eng.Job("allocate_port", container.ID)
  967. job.Setenv("HostIP", b.HostIp)
  968. job.Setenv("HostPort", b.HostPort)
  969. job.Setenv("Proto", port.Proto())
  970. job.Setenv("ContainerPort", port.Port())
  971. portEnv, err := job.Stdout.AddEnv()
  972. if err != nil {
  973. return err
  974. }
  975. if err := job.Run(); err != nil {
  976. eng.Job("release_interface", container.ID).Run()
  977. return err
  978. }
  979. b.HostIp = portEnv.Get("HostIP")
  980. b.HostPort = portEnv.Get("HostPort")
  981. binding[i] = b
  982. }
  983. bindings[port] = binding
  984. return nil
  985. }
  986. func (container *Container) GetProcessLabel() string {
  987. // even if we have a process label return "" if we are running
  988. // in privileged mode
  989. if container.hostConfig.Privileged {
  990. return ""
  991. }
  992. return container.ProcessLabel
  993. }
  994. func (container *Container) GetMountLabel() string {
  995. if container.hostConfig.Privileged {
  996. return ""
  997. }
  998. return container.MountLabel
  999. }
  1000. func (container *Container) getNetworkedContainer() (*Container, error) {
  1001. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  1002. switch parts[0] {
  1003. case "container":
  1004. nc := container.daemon.Get(parts[1])
  1005. if nc == nil {
  1006. return nil, fmt.Errorf("no such container to join network: %s", parts[1])
  1007. }
  1008. if !nc.IsRunning() {
  1009. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  1010. }
  1011. return nc, nil
  1012. default:
  1013. return nil, fmt.Errorf("network mode not set to container")
  1014. }
  1015. }
  1016. func (container *Container) GetVolumes() (map[string]*Volume, error) {
  1017. // Get all the bind-mounts
  1018. volumes, err := container.getBindMap()
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. // Get all the normal volumes
  1023. for volPath, hostPath := range container.Volumes {
  1024. if _, exists := volumes[volPath]; exists {
  1025. continue
  1026. }
  1027. volumes[volPath] = &Volume{VolPath: volPath, HostPath: hostPath, isReadWrite: container.VolumesRW[volPath]}
  1028. }
  1029. return volumes, nil
  1030. }
  1031. func (container *Container) getBindMap() (map[string]*Volume, error) {
  1032. var (
  1033. // Create the requested bind mounts
  1034. volumes = map[string]*Volume{}
  1035. // Define illegal container destinations
  1036. illegalDsts = []string{"/", "."}
  1037. )
  1038. for _, bind := range container.hostConfig.Binds {
  1039. vol, err := parseBindVolumeSpec(bind)
  1040. if err != nil {
  1041. return nil, err
  1042. }
  1043. vol.isBindMount = true
  1044. // Bail if trying to mount to an illegal destination
  1045. for _, illegal := range illegalDsts {
  1046. if vol.VolPath == illegal {
  1047. return nil, fmt.Errorf("Illegal bind destination: %s", vol.VolPath)
  1048. }
  1049. }
  1050. volumes[filepath.Clean(vol.VolPath)] = &vol
  1051. }
  1052. return volumes, nil
  1053. }