container.go 32 KB

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