container.go 30 KB

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