container.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. package docker
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/dotcloud/docker/archive"
  7. "github.com/dotcloud/docker/execdriver"
  8. "github.com/dotcloud/docker/graphdriver"
  9. "github.com/dotcloud/docker/pkg/cgroups"
  10. "github.com/dotcloud/docker/pkg/mount"
  11. "github.com/dotcloud/docker/pkg/term"
  12. "github.com/dotcloud/docker/utils"
  13. "github.com/kr/pty"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "net"
  18. "os"
  19. "path"
  20. "strings"
  21. "sync"
  22. "syscall"
  23. "time"
  24. )
  25. var (
  26. ErrNotATTY = errors.New("The PTY is not a file")
  27. ErrNoTTY = errors.New("No PTY found")
  28. )
  29. type Container struct {
  30. sync.Mutex
  31. root string // Path to the "home" of the container, including metadata.
  32. rootfs string // Path to the root filesystem of the container.
  33. ID string
  34. Created time.Time
  35. Path string
  36. Args []string
  37. Config *Config
  38. State State
  39. Image string
  40. network *NetworkInterface
  41. NetworkSettings *NetworkSettings
  42. ResolvConfPath string
  43. HostnamePath string
  44. HostsPath string
  45. Name string
  46. Driver string
  47. process *execdriver.Process
  48. stdout *utils.WriteBroadcaster
  49. stderr *utils.WriteBroadcaster
  50. stdin io.ReadCloser
  51. stdinPipe io.WriteCloser
  52. ptyMaster io.Closer
  53. runtime *Runtime
  54. waitLock chan struct{}
  55. Volumes map[string]string
  56. // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk.
  57. // Easier than migrating older container configs :)
  58. VolumesRW map[string]bool
  59. hostConfig *HostConfig
  60. activeLinks map[string]*Link
  61. }
  62. // Note: the Config structure should hold only portable information about the container.
  63. // Here, "portable" means "independent from the host we are running on".
  64. // Non-portable information *should* appear in HostConfig.
  65. type Config struct {
  66. Hostname string
  67. Domainname string
  68. User string
  69. Memory int64 // Memory limit (in bytes)
  70. MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
  71. CpuShares int64 // CPU shares (relative weight vs. other containers)
  72. AttachStdin bool
  73. AttachStdout bool
  74. AttachStderr bool
  75. PortSpecs []string // Deprecated - Can be in the format of 8080/tcp
  76. ExposedPorts map[Port]struct{}
  77. Tty bool // Attach standard streams to a tty, including stdin if it is not closed.
  78. OpenStdin bool // Open stdin
  79. StdinOnce bool // If true, close stdin after the 1 attached client disconnects.
  80. Env []string
  81. Cmd []string
  82. Dns []string
  83. Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
  84. Volumes map[string]struct{}
  85. VolumesFrom string
  86. WorkingDir string
  87. Entrypoint []string
  88. NetworkDisabled bool
  89. }
  90. type HostConfig struct {
  91. Binds []string
  92. ContainerIDFile string
  93. LxcConf []KeyValuePair
  94. Privileged bool
  95. PortBindings map[Port][]PortBinding
  96. Links []string
  97. PublishAllPorts bool
  98. }
  99. type BindMap struct {
  100. SrcPath string
  101. DstPath string
  102. Mode string
  103. }
  104. var (
  105. ErrContainerStart = errors.New("The container failed to start. Unknown error")
  106. ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.")
  107. ErrInvalidWorikingDirectory = errors.New("The working directory is invalid. It needs to be an absolute path.")
  108. ErrConflictAttachDetach = errors.New("Conflicting options: -a and -d")
  109. ErrConflictDetachAutoRemove = errors.New("Conflicting options: -rm and -d")
  110. )
  111. type KeyValuePair struct {
  112. Key string
  113. Value string
  114. }
  115. type PortBinding struct {
  116. HostIp string
  117. HostPort string
  118. }
  119. // 80/tcp
  120. type Port string
  121. func (p Port) Proto() string {
  122. parts := strings.Split(string(p), "/")
  123. if len(parts) == 1 {
  124. return "tcp"
  125. }
  126. return parts[1]
  127. }
  128. func (p Port) Port() string {
  129. return strings.Split(string(p), "/")[0]
  130. }
  131. func (p Port) Int() int {
  132. i, err := parsePort(p.Port())
  133. if err != nil {
  134. panic(err)
  135. }
  136. return i
  137. }
  138. func NewPort(proto, port string) Port {
  139. return Port(fmt.Sprintf("%s/%s", port, proto))
  140. }
  141. type PortMapping map[string]string // Deprecated
  142. type NetworkSettings struct {
  143. IPAddress string
  144. IPPrefixLen int
  145. Gateway string
  146. Bridge string
  147. PortMapping map[string]PortMapping // Deprecated
  148. Ports map[Port][]PortBinding
  149. }
  150. func (settings *NetworkSettings) PortMappingAPI() []APIPort {
  151. var mapping []APIPort
  152. for port, bindings := range settings.Ports {
  153. p, _ := parsePort(port.Port())
  154. if len(bindings) == 0 {
  155. mapping = append(mapping, APIPort{
  156. PublicPort: int64(p),
  157. Type: port.Proto(),
  158. })
  159. continue
  160. }
  161. for _, binding := range bindings {
  162. p, _ := parsePort(port.Port())
  163. h, _ := parsePort(binding.HostPort)
  164. mapping = append(mapping, APIPort{
  165. PrivatePort: int64(p),
  166. PublicPort: int64(h),
  167. Type: port.Proto(),
  168. IP: binding.HostIp,
  169. })
  170. }
  171. }
  172. return mapping
  173. }
  174. // Inject the io.Reader at the given path. Note: do not close the reader
  175. func (container *Container) Inject(file io.Reader, pth string) error {
  176. if err := container.EnsureMounted(); err != nil {
  177. return fmt.Errorf("inject: error mounting container %s: %s", container.ID, err)
  178. }
  179. // Return error if path exists
  180. destPath := path.Join(container.RootfsPath(), pth)
  181. if _, err := os.Stat(destPath); err == nil {
  182. // Since err is nil, the path could be stat'd and it exists
  183. return fmt.Errorf("%s exists", pth)
  184. } else if !os.IsNotExist(err) {
  185. // Expect err might be that the file doesn't exist, so
  186. // if it's some other error, return that.
  187. return err
  188. }
  189. // Make sure the directory exists
  190. if err := os.MkdirAll(path.Join(container.RootfsPath(), path.Dir(pth)), 0755); err != nil {
  191. return err
  192. }
  193. dest, err := os.Create(destPath)
  194. if err != nil {
  195. return err
  196. }
  197. defer dest.Close()
  198. if _, err := io.Copy(dest, file); err != nil {
  199. return err
  200. }
  201. return nil
  202. }
  203. func (container *Container) When() time.Time {
  204. return container.Created
  205. }
  206. func (container *Container) FromDisk() error {
  207. data, err := ioutil.ReadFile(container.jsonPath())
  208. if err != nil {
  209. return err
  210. }
  211. // Load container settings
  212. // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it
  213. if err := json.Unmarshal(data, container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
  214. return err
  215. }
  216. return container.readHostConfig()
  217. }
  218. func (container *Container) ToDisk() (err error) {
  219. data, err := json.Marshal(container)
  220. if err != nil {
  221. return
  222. }
  223. err = ioutil.WriteFile(container.jsonPath(), data, 0666)
  224. if err != nil {
  225. return
  226. }
  227. return container.writeHostConfig()
  228. }
  229. func (container *Container) readHostConfig() error {
  230. container.hostConfig = &HostConfig{}
  231. // If the hostconfig file does not exist, do not read it.
  232. // (We still have to initialize container.hostConfig,
  233. // but that's OK, since we just did that above.)
  234. _, err := os.Stat(container.hostConfigPath())
  235. if os.IsNotExist(err) {
  236. return nil
  237. }
  238. data, err := ioutil.ReadFile(container.hostConfigPath())
  239. if err != nil {
  240. return err
  241. }
  242. return json.Unmarshal(data, container.hostConfig)
  243. }
  244. func (container *Container) writeHostConfig() (err error) {
  245. data, err := json.Marshal(container.hostConfig)
  246. if err != nil {
  247. return
  248. }
  249. return ioutil.WriteFile(container.hostConfigPath(), data, 0666)
  250. }
  251. func (container *Container) generateEnvConfig(env []string) error {
  252. data, err := json.Marshal(env)
  253. if err != nil {
  254. return err
  255. }
  256. p, err := container.EnvConfigPath()
  257. if err != nil {
  258. return err
  259. }
  260. ioutil.WriteFile(p, data, 0600)
  261. return nil
  262. }
  263. func (container *Container) setupPty() error {
  264. ptyMaster, ptySlave, err := pty.Open()
  265. if err != nil {
  266. return err
  267. }
  268. container.ptyMaster = ptyMaster
  269. container.process.Stdout = ptySlave
  270. container.process.Stderr = ptySlave
  271. // Copy the PTYs to our broadcasters
  272. go func() {
  273. defer container.stdout.CloseWriters()
  274. utils.Debugf("startPty: begin of stdout pipe")
  275. io.Copy(container.stdout, ptyMaster)
  276. utils.Debugf("startPty: end of stdout pipe")
  277. }()
  278. // stdin
  279. if container.Config.OpenStdin {
  280. container.process.Stdin = ptySlave
  281. container.process.SysProcAttr.Setctty = true
  282. go func() {
  283. defer container.stdin.Close()
  284. utils.Debugf("startPty: begin of stdin pipe")
  285. io.Copy(ptyMaster, container.stdin)
  286. utils.Debugf("startPty: end of stdin pipe")
  287. }()
  288. }
  289. return nil
  290. }
  291. func (container *Container) setupStd() error {
  292. container.process.Stdout = container.stdout
  293. container.process.Stderr = container.stderr
  294. if container.Config.OpenStdin {
  295. stdin, err := container.process.StdinPipe()
  296. if err != nil {
  297. return err
  298. }
  299. go func() {
  300. defer stdin.Close()
  301. utils.Debugf("start: begin of stdin pipe")
  302. io.Copy(stdin, container.stdin)
  303. utils.Debugf("start: end of stdin pipe")
  304. }()
  305. }
  306. return nil
  307. }
  308. func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error {
  309. var cStdout, cStderr io.ReadCloser
  310. var nJobs int
  311. errors := make(chan error, 3)
  312. if stdin != nil && container.Config.OpenStdin {
  313. nJobs += 1
  314. if cStdin, err := container.StdinPipe(); err != nil {
  315. errors <- err
  316. } else {
  317. go func() {
  318. utils.Debugf("attach: stdin: begin")
  319. defer utils.Debugf("attach: stdin: end")
  320. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  321. if container.Config.StdinOnce && !container.Config.Tty {
  322. defer cStdin.Close()
  323. } else {
  324. defer func() {
  325. if cStdout != nil {
  326. cStdout.Close()
  327. }
  328. if cStderr != nil {
  329. cStderr.Close()
  330. }
  331. }()
  332. }
  333. if container.Config.Tty {
  334. _, err = utils.CopyEscapable(cStdin, stdin)
  335. } else {
  336. _, err = io.Copy(cStdin, stdin)
  337. }
  338. if err == io.ErrClosedPipe {
  339. err = nil
  340. }
  341. if err != nil {
  342. utils.Errorf("attach: stdin: %s", err)
  343. }
  344. errors <- err
  345. }()
  346. }
  347. }
  348. if stdout != nil {
  349. nJobs += 1
  350. if p, err := container.StdoutPipe(); err != nil {
  351. errors <- err
  352. } else {
  353. cStdout = p
  354. go func() {
  355. utils.Debugf("attach: stdout: begin")
  356. defer utils.Debugf("attach: stdout: end")
  357. // If we are in StdinOnce mode, then close stdin
  358. if container.Config.StdinOnce && stdin != nil {
  359. defer stdin.Close()
  360. }
  361. if stdinCloser != nil {
  362. defer stdinCloser.Close()
  363. }
  364. _, err := io.Copy(stdout, cStdout)
  365. if err == io.ErrClosedPipe {
  366. err = nil
  367. }
  368. if err != nil {
  369. utils.Errorf("attach: stdout: %s", err)
  370. }
  371. errors <- err
  372. }()
  373. }
  374. } else {
  375. go func() {
  376. if stdinCloser != nil {
  377. defer stdinCloser.Close()
  378. }
  379. if cStdout, err := container.StdoutPipe(); err != nil {
  380. utils.Errorf("attach: stdout pipe: %s", err)
  381. } else {
  382. io.Copy(&utils.NopWriter{}, cStdout)
  383. }
  384. }()
  385. }
  386. if stderr != nil {
  387. nJobs += 1
  388. if p, err := container.StderrPipe(); err != nil {
  389. errors <- err
  390. } else {
  391. cStderr = p
  392. go func() {
  393. utils.Debugf("attach: stderr: begin")
  394. defer utils.Debugf("attach: stderr: end")
  395. // If we are in StdinOnce mode, then close stdin
  396. if container.Config.StdinOnce && stdin != nil {
  397. defer stdin.Close()
  398. }
  399. if stdinCloser != nil {
  400. defer stdinCloser.Close()
  401. }
  402. _, err := io.Copy(stderr, cStderr)
  403. if err == io.ErrClosedPipe {
  404. err = nil
  405. }
  406. if err != nil {
  407. utils.Errorf("attach: stderr: %s", err)
  408. }
  409. errors <- err
  410. }()
  411. }
  412. } else {
  413. go func() {
  414. if stdinCloser != nil {
  415. defer stdinCloser.Close()
  416. }
  417. if cStderr, err := container.StderrPipe(); err != nil {
  418. utils.Errorf("attach: stdout pipe: %s", err)
  419. } else {
  420. io.Copy(&utils.NopWriter{}, cStderr)
  421. }
  422. }()
  423. }
  424. return utils.Go(func() error {
  425. defer func() {
  426. if cStdout != nil {
  427. cStdout.Close()
  428. }
  429. if cStderr != nil {
  430. cStderr.Close()
  431. }
  432. }()
  433. // FIXME: how to clean up the stdin goroutine without the unwanted side effect
  434. // of closing the passed stdin? Add an intermediary io.Pipe?
  435. for i := 0; i < nJobs; i += 1 {
  436. utils.Debugf("attach: waiting for job %d/%d", i+1, nJobs)
  437. if err := <-errors; err != nil {
  438. utils.Errorf("attach: job %d returned error %s, aborting all jobs", i+1, err)
  439. return err
  440. }
  441. utils.Debugf("attach: job %d completed successfully", i+1)
  442. }
  443. utils.Debugf("attach: all jobs completed successfully")
  444. return nil
  445. })
  446. }
  447. func (container *Container) Start() (err error) {
  448. container.Lock()
  449. defer container.Unlock()
  450. if container.State.IsRunning() {
  451. return fmt.Errorf("The container %s is already running.", container.ID)
  452. }
  453. defer func() {
  454. if err != nil {
  455. container.cleanup()
  456. }
  457. }()
  458. if err := container.EnsureMounted(); err != nil {
  459. return err
  460. }
  461. if container.runtime.networkManager.disabled {
  462. container.Config.NetworkDisabled = true
  463. container.buildHostnameAndHostsFiles("127.0.1.1")
  464. } else {
  465. if err := container.allocateNetwork(); err != nil {
  466. return err
  467. }
  468. container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  469. }
  470. // Make sure the config is compatible with the current kernel
  471. if container.Config.Memory > 0 && !container.runtime.sysInfo.MemoryLimit {
  472. log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  473. container.Config.Memory = 0
  474. }
  475. if container.Config.Memory > 0 && !container.runtime.sysInfo.SwapLimit {
  476. log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  477. container.Config.MemorySwap = -1
  478. }
  479. if container.runtime.sysInfo.IPv4ForwardingDisabled {
  480. log.Printf("WARNING: IPv4 forwarding is disabled. Networking will not work")
  481. }
  482. if container.Volumes == nil || len(container.Volumes) == 0 {
  483. container.Volumes = make(map[string]string)
  484. container.VolumesRW = make(map[string]bool)
  485. }
  486. // Apply volumes from another container if requested
  487. if err := container.applyExternalVolumes(); err != nil {
  488. return err
  489. }
  490. if err := container.createVolumes(); err != nil {
  491. return err
  492. }
  493. // Setup environment
  494. env := []string{
  495. "HOME=/",
  496. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  497. "HOSTNAME=" + container.Config.Hostname,
  498. }
  499. if container.Config.Tty {
  500. env = append(env, "TERM=xterm")
  501. }
  502. // Init any links between the parent and children
  503. runtime := container.runtime
  504. children, err := runtime.Children(container.Name)
  505. if err != nil {
  506. return err
  507. }
  508. if len(children) > 0 {
  509. container.activeLinks = make(map[string]*Link, len(children))
  510. // If we encounter an error make sure that we rollback any network
  511. // config and ip table changes
  512. rollback := func() {
  513. for _, link := range container.activeLinks {
  514. link.Disable()
  515. }
  516. container.activeLinks = nil
  517. }
  518. for p, child := range children {
  519. link, err := NewLink(container, child, p, runtime.networkManager.bridgeIface)
  520. if err != nil {
  521. rollback()
  522. return err
  523. }
  524. container.activeLinks[link.Alias()] = link
  525. if err := link.Enable(); err != nil {
  526. rollback()
  527. return err
  528. }
  529. for _, envVar := range link.ToEnv() {
  530. env = append(env, envVar)
  531. }
  532. }
  533. }
  534. for _, elem := range container.Config.Env {
  535. env = append(env, elem)
  536. }
  537. if err := container.generateEnvConfig(env); err != nil {
  538. return err
  539. }
  540. var workingDir string
  541. if container.Config.WorkingDir != "" {
  542. workingDir = path.Clean(container.Config.WorkingDir)
  543. if err := os.MkdirAll(path.Join(container.RootfsPath(), workingDir), 0755); err != nil {
  544. return nil
  545. }
  546. }
  547. root := container.RootfsPath()
  548. envPath, err := container.EnvConfigPath()
  549. if err != nil {
  550. return err
  551. }
  552. // Mount docker specific files into the containers root fs
  553. if err := mount.Mount(runtime.sysInitPath, path.Join(root, "/.dockerinit"), "none", "bind,ro"); err != nil {
  554. return err
  555. }
  556. if err := mount.Mount(envPath, path.Join(root, "/.dockerenv"), "none", "bind,ro"); err != nil {
  557. return err
  558. }
  559. if err := mount.Mount(container.ResolvConfPath, path.Join(root, "/etc/resolv.conf"), "none", "bind,ro"); err != nil {
  560. return err
  561. }
  562. if container.HostnamePath != "" && container.HostsPath != "" {
  563. if err := mount.Mount(container.HostnamePath, path.Join(root, "/etc/hostname"), "none", "bind,ro"); err != nil {
  564. return err
  565. }
  566. if err := mount.Mount(container.HostsPath, path.Join(root, "/etc/hosts"), "none", "bind,ro"); err != nil {
  567. return err
  568. }
  569. }
  570. // Mount user specified volumes
  571. for r, v := range container.Volumes {
  572. mountAs := "ro"
  573. if container.VolumesRW[r] {
  574. mountAs = "rw"
  575. }
  576. if err := mount.Mount(v, path.Join(root, r), "none", fmt.Sprintf("bind,%s", mountAs)); err != nil {
  577. return err
  578. }
  579. }
  580. var (
  581. en *execdriver.Network
  582. driverConfig []string
  583. )
  584. if !container.Config.NetworkDisabled {
  585. network := container.NetworkSettings
  586. en = &execdriver.Network{
  587. Gateway: network.Gateway,
  588. Bridge: network.Bridge,
  589. IPAddress: network.IPAddress,
  590. IPPrefixLen: network.IPPrefixLen,
  591. Mtu: container.runtime.config.Mtu,
  592. }
  593. }
  594. if lxcConf := container.hostConfig.LxcConf; lxcConf != nil {
  595. for _, pair := range lxcConf {
  596. driverConfig = append(driverConfig, fmt.Sprintf("%s = %s", pair.Key, pair.Value))
  597. }
  598. }
  599. cgroupValues := &cgroups.Values{
  600. Memory: container.Config.Memory,
  601. MemorySwap: container.Config.MemorySwap,
  602. CpuShares: container.Config.CpuShares,
  603. }
  604. container.process = &execdriver.Process{
  605. ID: container.ID,
  606. Privileged: container.hostConfig.Privileged,
  607. Rootfs: root,
  608. InitPath: "/.dockerinit",
  609. Entrypoint: container.Path,
  610. Arguments: container.Args,
  611. WorkingDir: workingDir,
  612. Network: en,
  613. Tty: container.Config.Tty,
  614. User: container.Config.User,
  615. Config: driverConfig,
  616. Cgroups: cgroupValues,
  617. }
  618. container.process.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  619. // Setup logging of stdout and stderr to disk
  620. if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil {
  621. return err
  622. }
  623. if err := container.runtime.LogToDisk(container.stderr, container.logPath("json"), "stderr"); err != nil {
  624. return err
  625. }
  626. container.waitLock = make(chan struct{})
  627. // Setuping pipes and/or Pty
  628. var setup func() error
  629. if container.Config.Tty {
  630. setup = container.setupPty
  631. } else {
  632. setup = container.setupStd
  633. }
  634. if err := setup(); err != nil {
  635. return err
  636. }
  637. callbackLock := make(chan struct{})
  638. callback := func(process *execdriver.Process) {
  639. container.State.SetRunning(process.Pid())
  640. if process.Tty {
  641. // The callback is called after the process Start()
  642. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlace
  643. // which we close here.
  644. if c, ok := process.Stdout.(io.Closer); ok {
  645. c.Close()
  646. }
  647. }
  648. if err := container.ToDisk(); err != nil {
  649. utils.Debugf("%s", err)
  650. }
  651. close(callbackLock)
  652. }
  653. // We use a callback here instead of a goroutine and an chan for
  654. // syncronization purposes
  655. cErr := utils.Go(func() error { return container.monitor(callback) })
  656. // Start should not return until the process is actually running
  657. select {
  658. case <-callbackLock:
  659. case err := <-cErr:
  660. return err
  661. }
  662. return nil
  663. }
  664. func (container *Container) getBindMap() (map[string]BindMap, error) {
  665. // Create the requested bind mounts
  666. binds := make(map[string]BindMap)
  667. // Define illegal container destinations
  668. illegalDsts := []string{"/", "."}
  669. for _, bind := range container.hostConfig.Binds {
  670. // FIXME: factorize bind parsing in parseBind
  671. var src, dst, mode string
  672. arr := strings.Split(bind, ":")
  673. if len(arr) == 2 {
  674. src = arr[0]
  675. dst = arr[1]
  676. mode = "rw"
  677. } else if len(arr) == 3 {
  678. src = arr[0]
  679. dst = arr[1]
  680. mode = arr[2]
  681. } else {
  682. return nil, fmt.Errorf("Invalid bind specification: %s", bind)
  683. }
  684. // Bail if trying to mount to an illegal destination
  685. for _, illegal := range illegalDsts {
  686. if dst == illegal {
  687. return nil, fmt.Errorf("Illegal bind destination: %s", dst)
  688. }
  689. }
  690. bindMap := BindMap{
  691. SrcPath: src,
  692. DstPath: dst,
  693. Mode: mode,
  694. }
  695. binds[path.Clean(dst)] = bindMap
  696. }
  697. return binds, nil
  698. }
  699. func (container *Container) createVolumes() error {
  700. binds, err := container.getBindMap()
  701. if err != nil {
  702. return err
  703. }
  704. volumesDriver := container.runtime.volumes.driver
  705. // Create the requested volumes if they don't exist
  706. for volPath := range container.Config.Volumes {
  707. volPath = path.Clean(volPath)
  708. volIsDir := true
  709. // Skip existing volumes
  710. if _, exists := container.Volumes[volPath]; exists {
  711. continue
  712. }
  713. var srcPath string
  714. var isBindMount bool
  715. srcRW := false
  716. // If an external bind is defined for this volume, use that as a source
  717. if bindMap, exists := binds[volPath]; exists {
  718. isBindMount = true
  719. srcPath = bindMap.SrcPath
  720. if strings.ToLower(bindMap.Mode) == "rw" {
  721. srcRW = true
  722. }
  723. if stat, err := os.Lstat(bindMap.SrcPath); err != nil {
  724. return err
  725. } else {
  726. volIsDir = stat.IsDir()
  727. }
  728. // Otherwise create an directory in $ROOT/volumes/ and use that
  729. } else {
  730. // Do not pass a container as the parameter for the volume creation.
  731. // The graph driver using the container's information ( Image ) to
  732. // create the parent.
  733. c, err := container.runtime.volumes.Create(nil, nil, "", "", nil)
  734. if err != nil {
  735. return err
  736. }
  737. srcPath, err = volumesDriver.Get(c.ID)
  738. if err != nil {
  739. return fmt.Errorf("Driver %s failed to get volume rootfs %s: %s", volumesDriver, c.ID, err)
  740. }
  741. srcRW = true // RW by default
  742. }
  743. container.Volumes[volPath] = srcPath
  744. container.VolumesRW[volPath] = srcRW
  745. // Create the mountpoint
  746. volPath = path.Join(container.RootfsPath(), volPath)
  747. rootVolPath, err := utils.FollowSymlinkInScope(volPath, container.RootfsPath())
  748. if err != nil {
  749. return err
  750. }
  751. if _, err := os.Stat(rootVolPath); err != nil {
  752. if os.IsNotExist(err) {
  753. if volIsDir {
  754. if err := os.MkdirAll(rootVolPath, 0755); err != nil {
  755. return err
  756. }
  757. } else {
  758. if err := os.MkdirAll(path.Dir(rootVolPath), 0755); err != nil {
  759. return err
  760. }
  761. if f, err := os.OpenFile(rootVolPath, os.O_CREATE, 0755); err != nil {
  762. return err
  763. } else {
  764. f.Close()
  765. }
  766. }
  767. }
  768. }
  769. // Do not copy or change permissions if we are mounting from the host
  770. if srcRW && !isBindMount {
  771. volList, err := ioutil.ReadDir(rootVolPath)
  772. if err != nil {
  773. return err
  774. }
  775. if len(volList) > 0 {
  776. srcList, err := ioutil.ReadDir(srcPath)
  777. if err != nil {
  778. return err
  779. }
  780. if len(srcList) == 0 {
  781. // If the source volume is empty copy files from the root into the volume
  782. if err := archive.CopyWithTar(rootVolPath, srcPath); err != nil {
  783. return err
  784. }
  785. var stat syscall.Stat_t
  786. if err := syscall.Stat(rootVolPath, &stat); err != nil {
  787. return err
  788. }
  789. var srcStat syscall.Stat_t
  790. if err := syscall.Stat(srcPath, &srcStat); err != nil {
  791. return err
  792. }
  793. // Change the source volume's ownership if it differs from the root
  794. // files that where just copied
  795. if stat.Uid != srcStat.Uid || stat.Gid != srcStat.Gid {
  796. if err := os.Chown(srcPath, int(stat.Uid), int(stat.Gid)); err != nil {
  797. return err
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. return nil
  805. }
  806. func (container *Container) applyExternalVolumes() error {
  807. if container.Config.VolumesFrom != "" {
  808. containerSpecs := strings.Split(container.Config.VolumesFrom, ",")
  809. for _, containerSpec := range containerSpecs {
  810. mountRW := true
  811. specParts := strings.SplitN(containerSpec, ":", 2)
  812. switch len(specParts) {
  813. case 0:
  814. return fmt.Errorf("Malformed volumes-from specification: %s", container.Config.VolumesFrom)
  815. case 2:
  816. switch specParts[1] {
  817. case "ro":
  818. mountRW = false
  819. case "rw": // mountRW is already true
  820. default:
  821. return fmt.Errorf("Malformed volumes-from speficication: %s", containerSpec)
  822. }
  823. }
  824. c := container.runtime.Get(specParts[0])
  825. if c == nil {
  826. return fmt.Errorf("Container %s not found. Impossible to mount its volumes", container.ID)
  827. }
  828. for volPath, id := range c.Volumes {
  829. if _, exists := container.Volumes[volPath]; exists {
  830. continue
  831. }
  832. if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil {
  833. return err
  834. }
  835. container.Volumes[volPath] = id
  836. if isRW, exists := c.VolumesRW[volPath]; exists {
  837. container.VolumesRW[volPath] = isRW && mountRW
  838. }
  839. }
  840. }
  841. }
  842. return nil
  843. }
  844. func (container *Container) Run() error {
  845. if err := container.Start(); err != nil {
  846. return err
  847. }
  848. container.Wait()
  849. return nil
  850. }
  851. func (container *Container) Output() (output []byte, err error) {
  852. pipe, err := container.StdoutPipe()
  853. if err != nil {
  854. return nil, err
  855. }
  856. defer pipe.Close()
  857. if err := container.Start(); err != nil {
  858. return nil, err
  859. }
  860. output, err = ioutil.ReadAll(pipe)
  861. container.Wait()
  862. return output, err
  863. }
  864. // Container.StdinPipe returns a WriteCloser which can be used to feed data
  865. // to the standard input of the container's active process.
  866. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser
  867. // which can be used to retrieve the standard output (and error) generated
  868. // by the container's active process. The output (and error) are actually
  869. // copied and delivered to all StdoutPipe and StderrPipe consumers, using
  870. // a kind of "broadcaster".
  871. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  872. return container.stdinPipe, nil
  873. }
  874. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  875. reader, writer := io.Pipe()
  876. container.stdout.AddWriter(writer, "")
  877. return utils.NewBufReader(reader), nil
  878. }
  879. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  880. reader, writer := io.Pipe()
  881. container.stderr.AddWriter(writer, "")
  882. return utils.NewBufReader(reader), nil
  883. }
  884. func (container *Container) buildHostnameAndHostsFiles(IP string) {
  885. container.HostnamePath = path.Join(container.root, "hostname")
  886. ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  887. hostsContent := []byte(`
  888. 127.0.0.1 localhost
  889. ::1 localhost ip6-localhost ip6-loopback
  890. fe00::0 ip6-localnet
  891. ff00::0 ip6-mcastprefix
  892. ff02::1 ip6-allnodes
  893. ff02::2 ip6-allrouters
  894. `)
  895. container.HostsPath = path.Join(container.root, "hosts")
  896. if container.Config.Domainname != "" {
  897. hostsContent = append([]byte(fmt.Sprintf("%s\t%s.%s %s\n", IP, container.Config.Hostname, container.Config.Domainname, container.Config.Hostname)), hostsContent...)
  898. } else if !container.Config.NetworkDisabled {
  899. hostsContent = append([]byte(fmt.Sprintf("%s\t%s\n", IP, container.Config.Hostname)), hostsContent...)
  900. }
  901. ioutil.WriteFile(container.HostsPath, hostsContent, 0644)
  902. }
  903. func (container *Container) allocateNetwork() error {
  904. if container.Config.NetworkDisabled {
  905. return nil
  906. }
  907. var (
  908. iface *NetworkInterface
  909. err error
  910. )
  911. if container.State.IsGhost() {
  912. if manager := container.runtime.networkManager; manager.disabled {
  913. iface = &NetworkInterface{disabled: true}
  914. } else {
  915. iface = &NetworkInterface{
  916. IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask},
  917. Gateway: manager.bridgeNetwork.IP,
  918. manager: manager,
  919. }
  920. if iface != nil && iface.IPNet.IP != nil {
  921. ipNum := ipToInt(iface.IPNet.IP)
  922. manager.ipAllocator.inUse[ipNum] = struct{}{}
  923. } else {
  924. iface, err = container.runtime.networkManager.Allocate()
  925. if err != nil {
  926. return err
  927. }
  928. }
  929. }
  930. } else {
  931. iface, err = container.runtime.networkManager.Allocate()
  932. if err != nil {
  933. return err
  934. }
  935. }
  936. if container.Config.PortSpecs != nil {
  937. utils.Debugf("Migrating port mappings for container: %s", strings.Join(container.Config.PortSpecs, ", "))
  938. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  939. return err
  940. }
  941. container.Config.PortSpecs = nil
  942. if err := container.writeHostConfig(); err != nil {
  943. return err
  944. }
  945. }
  946. var (
  947. portSpecs = make(map[Port]struct{})
  948. bindings = make(map[Port][]PortBinding)
  949. )
  950. if !container.State.IsGhost() {
  951. if container.Config.ExposedPorts != nil {
  952. portSpecs = container.Config.ExposedPorts
  953. }
  954. if container.hostConfig.PortBindings != nil {
  955. bindings = container.hostConfig.PortBindings
  956. }
  957. } else {
  958. if container.NetworkSettings.Ports != nil {
  959. for port, binding := range container.NetworkSettings.Ports {
  960. portSpecs[port] = struct{}{}
  961. bindings[port] = binding
  962. }
  963. }
  964. }
  965. container.NetworkSettings.PortMapping = nil
  966. for port := range portSpecs {
  967. binding := bindings[port]
  968. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  969. binding = append(binding, PortBinding{})
  970. }
  971. for i := 0; i < len(binding); i++ {
  972. b := binding[i]
  973. nat, err := iface.AllocatePort(port, b)
  974. if err != nil {
  975. iface.Release()
  976. return err
  977. }
  978. utils.Debugf("Allocate port: %s:%s->%s", nat.Binding.HostIp, port, nat.Binding.HostPort)
  979. binding[i] = nat.Binding
  980. }
  981. bindings[port] = binding
  982. }
  983. container.writeHostConfig()
  984. container.NetworkSettings.Ports = bindings
  985. container.network = iface
  986. container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface
  987. container.NetworkSettings.IPAddress = iface.IPNet.IP.String()
  988. container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size()
  989. container.NetworkSettings.Gateway = iface.Gateway.String()
  990. return nil
  991. }
  992. func (container *Container) releaseNetwork() {
  993. if container.Config.NetworkDisabled || container.network == nil {
  994. return
  995. }
  996. container.network.Release()
  997. container.network = nil
  998. container.NetworkSettings = &NetworkSettings{}
  999. }
  1000. func (container *Container) monitor(callback execdriver.StartCallback) error {
  1001. var (
  1002. err error
  1003. exitCode int
  1004. )
  1005. if container.process == nil {
  1006. // This happends when you have a GHOST container with lxc
  1007. err = container.runtime.WaitGhost(container)
  1008. } else {
  1009. exitCode, err = container.runtime.Run(container, callback)
  1010. }
  1011. if err != nil {
  1012. if container.runtime != nil && container.runtime.srv != nil {
  1013. container.runtime.srv.LogEvent("die", container.ID, container.runtime.repositories.ImageName(container.Image))
  1014. }
  1015. }
  1016. // Cleanup
  1017. container.cleanup()
  1018. // Re-create a brand new stdin pipe once the container exited
  1019. if container.Config.OpenStdin {
  1020. container.stdin, container.stdinPipe = io.Pipe()
  1021. }
  1022. container.State.SetStopped(exitCode)
  1023. close(container.waitLock)
  1024. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  1025. // If another goroutine was waiting for Wait() to return before removing the container's root
  1026. // from the filesystem... At this point it may already have done so.
  1027. // This is because State.setStopped() has already been called, and has caused Wait()
  1028. // to return.
  1029. // FIXME: why are we serializing running state to disk in the first place?
  1030. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
  1031. container.ToDisk()
  1032. return err
  1033. }
  1034. func (container *Container) cleanup() {
  1035. container.releaseNetwork()
  1036. // Disable all active links
  1037. if container.activeLinks != nil {
  1038. for _, link := range container.activeLinks {
  1039. link.Disable()
  1040. }
  1041. }
  1042. if container.Config.OpenStdin {
  1043. if err := container.stdin.Close(); err != nil {
  1044. utils.Errorf("%s: Error close stdin: %s", container.ID, err)
  1045. }
  1046. }
  1047. if err := container.stdout.CloseWriters(); err != nil {
  1048. utils.Errorf("%s: Error close stdout: %s", container.ID, err)
  1049. }
  1050. if err := container.stderr.CloseWriters(); err != nil {
  1051. utils.Errorf("%s: Error close stderr: %s", container.ID, err)
  1052. }
  1053. if container.ptyMaster != nil {
  1054. if err := container.ptyMaster.Close(); err != nil {
  1055. utils.Errorf("%s: Error closing Pty master: %s", container.ID, err)
  1056. }
  1057. }
  1058. if err := container.Unmount(); err != nil {
  1059. log.Printf("%v: Failed to umount filesystem: %v", container.ID, err)
  1060. }
  1061. }
  1062. func (container *Container) kill(sig int) error {
  1063. container.Lock()
  1064. defer container.Unlock()
  1065. if !container.State.IsRunning() {
  1066. return nil
  1067. }
  1068. return container.runtime.Kill(container, sig)
  1069. }
  1070. func (container *Container) Kill() error {
  1071. if !container.State.IsRunning() {
  1072. return nil
  1073. }
  1074. // 1. Send SIGKILL
  1075. if err := container.kill(9); err != nil {
  1076. return err
  1077. }
  1078. // 2. Wait for the process to die, in last resort, try to kill the process directly
  1079. if err := container.WaitTimeout(10 * time.Second); err != nil {
  1080. if container.process == nil {
  1081. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", utils.TruncateID(container.ID))
  1082. }
  1083. log.Printf("Container %s failed to exit within 10 seconds of lxc-kill %s - trying direct SIGKILL", "SIGKILL", utils.TruncateID(container.ID))
  1084. if err := container.runtime.Kill(container, 9); err != nil {
  1085. return err
  1086. }
  1087. }
  1088. container.Wait()
  1089. return nil
  1090. }
  1091. func (container *Container) Stop(seconds int) error {
  1092. if !container.State.IsRunning() {
  1093. return nil
  1094. }
  1095. // 1. Send a SIGTERM
  1096. if err := container.kill(15); err != nil {
  1097. utils.Debugf("Error sending kill SIGTERM: %s", err)
  1098. log.Print("Failed to send SIGTERM to the process, force killing")
  1099. if err := container.kill(9); err != nil {
  1100. return err
  1101. }
  1102. }
  1103. // 2. Wait for the process to exit on its own
  1104. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  1105. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  1106. // 3. If it doesn't, then send SIGKILL
  1107. if err := container.Kill(); err != nil {
  1108. return err
  1109. }
  1110. }
  1111. return nil
  1112. }
  1113. func (container *Container) Restart(seconds int) error {
  1114. if err := container.Stop(seconds); err != nil {
  1115. return err
  1116. }
  1117. return container.Start()
  1118. }
  1119. // Wait blocks until the container stops running, then returns its exit code.
  1120. func (container *Container) Wait() int {
  1121. <-container.waitLock
  1122. return container.State.GetExitCode()
  1123. }
  1124. func (container *Container) Resize(h, w int) error {
  1125. pty, ok := container.ptyMaster.(*os.File)
  1126. if !ok {
  1127. return fmt.Errorf("ptyMaster does not have Fd() method")
  1128. }
  1129. return term.SetWinsize(pty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  1130. }
  1131. func (container *Container) ExportRw() (archive.Archive, error) {
  1132. if err := container.EnsureMounted(); err != nil {
  1133. return nil, err
  1134. }
  1135. if container.runtime == nil {
  1136. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  1137. }
  1138. return container.runtime.Diff(container)
  1139. }
  1140. func (container *Container) Export() (archive.Archive, error) {
  1141. if err := container.EnsureMounted(); err != nil {
  1142. return nil, err
  1143. }
  1144. return archive.Tar(container.RootfsPath(), archive.Uncompressed)
  1145. }
  1146. func (container *Container) WaitTimeout(timeout time.Duration) error {
  1147. done := make(chan bool)
  1148. go func() {
  1149. container.Wait()
  1150. done <- true
  1151. }()
  1152. select {
  1153. case <-time.After(timeout):
  1154. return fmt.Errorf("Timed Out")
  1155. case <-done:
  1156. return nil
  1157. }
  1158. }
  1159. func (container *Container) EnsureMounted() error {
  1160. // FIXME: EnsureMounted is deprecated because drivers are now responsible
  1161. // for re-entrant mounting in their Get() method.
  1162. return container.Mount()
  1163. }
  1164. func (container *Container) Mount() error {
  1165. return container.runtime.Mount(container)
  1166. }
  1167. func (container *Container) Changes() ([]archive.Change, error) {
  1168. return container.runtime.Changes(container)
  1169. }
  1170. func (container *Container) GetImage() (*Image, error) {
  1171. if container.runtime == nil {
  1172. return nil, fmt.Errorf("Can't get image of unregistered container")
  1173. }
  1174. return container.runtime.graph.Get(container.Image)
  1175. }
  1176. func (container *Container) Unmount() error {
  1177. var (
  1178. err error
  1179. root = container.RootfsPath()
  1180. mounts = []string{
  1181. path.Join(root, "/.dockerinit"),
  1182. path.Join(root, "/.dockerenv"),
  1183. path.Join(root, "/etc/resolv.conf"),
  1184. }
  1185. )
  1186. if container.HostnamePath != "" && container.HostsPath != "" {
  1187. mounts = append(mounts, path.Join(root, "/etc/hostname"), path.Join(root, "/etc/hosts"))
  1188. }
  1189. for r := range container.Volumes {
  1190. mounts = append(mounts, path.Join(root, r))
  1191. }
  1192. for _, m := range mounts {
  1193. if lastError := mount.Unmount(m); lastError != nil {
  1194. err = lastError
  1195. }
  1196. }
  1197. if err != nil {
  1198. return err
  1199. }
  1200. return container.runtime.Unmount(container)
  1201. }
  1202. func (container *Container) logPath(name string) string {
  1203. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name))
  1204. }
  1205. func (container *Container) ReadLog(name string) (io.Reader, error) {
  1206. return os.Open(container.logPath(name))
  1207. }
  1208. func (container *Container) hostConfigPath() string {
  1209. return path.Join(container.root, "hostconfig.json")
  1210. }
  1211. func (container *Container) jsonPath() string {
  1212. return path.Join(container.root, "config.json")
  1213. }
  1214. func (container *Container) EnvConfigPath() (string, error) {
  1215. p := path.Join(container.root, "config.env")
  1216. if _, err := os.Stat(p); err != nil {
  1217. if os.IsNotExist(err) {
  1218. f, err := os.Create(p)
  1219. if err != nil {
  1220. return "", err
  1221. }
  1222. f.Close()
  1223. } else {
  1224. return "", err
  1225. }
  1226. }
  1227. return p, nil
  1228. }
  1229. // This method must be exported to be used from the lxc template
  1230. func (container *Container) RootfsPath() string {
  1231. return container.rootfs
  1232. }
  1233. func validateID(id string) error {
  1234. if id == "" {
  1235. return fmt.Errorf("Invalid empty id")
  1236. }
  1237. return nil
  1238. }
  1239. // GetSize, return real size, virtual size
  1240. func (container *Container) GetSize() (int64, int64) {
  1241. var (
  1242. sizeRw, sizeRootfs int64
  1243. err error
  1244. driver = container.runtime.driver
  1245. )
  1246. if err := container.EnsureMounted(); err != nil {
  1247. utils.Errorf("Warning: failed to compute size of container rootfs %s: %s", container.ID, err)
  1248. return sizeRw, sizeRootfs
  1249. }
  1250. if differ, ok := container.runtime.driver.(graphdriver.Differ); ok {
  1251. sizeRw, err = differ.DiffSize(container.ID)
  1252. if err != nil {
  1253. utils.Errorf("Warning: driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  1254. // FIXME: GetSize should return an error. Not changing it now in case
  1255. // there is a side-effect.
  1256. sizeRw = -1
  1257. }
  1258. } else {
  1259. changes, _ := container.Changes()
  1260. if changes != nil {
  1261. sizeRw = archive.ChangesSize(container.RootfsPath(), changes)
  1262. } else {
  1263. sizeRw = -1
  1264. }
  1265. }
  1266. if _, err = os.Stat(container.RootfsPath()); err != nil {
  1267. if sizeRootfs, err = utils.TreeSize(container.RootfsPath()); err != nil {
  1268. sizeRootfs = -1
  1269. }
  1270. }
  1271. return sizeRw, sizeRootfs
  1272. }
  1273. func (container *Container) Copy(resource string) (archive.Archive, error) {
  1274. if err := container.EnsureMounted(); err != nil {
  1275. return nil, err
  1276. }
  1277. var filter []string
  1278. basePath := path.Join(container.RootfsPath(), resource)
  1279. stat, err := os.Stat(basePath)
  1280. if err != nil {
  1281. return nil, err
  1282. }
  1283. if !stat.IsDir() {
  1284. d, f := path.Split(basePath)
  1285. basePath = d
  1286. filter = []string{f}
  1287. } else {
  1288. filter = []string{path.Base(basePath)}
  1289. basePath = path.Dir(basePath)
  1290. }
  1291. return archive.TarFilter(basePath, &archive.TarOptions{
  1292. Compression: archive.Uncompressed,
  1293. Includes: filter,
  1294. Recursive: true,
  1295. })
  1296. }
  1297. // Returns true if the container exposes a certain port
  1298. func (container *Container) Exposes(p Port) bool {
  1299. _, exists := container.Config.ExposedPorts[p]
  1300. return exists
  1301. }
  1302. func (container *Container) GetPtyMaster() (*os.File, error) {
  1303. if container.ptyMaster == nil {
  1304. return nil, ErrNoTTY
  1305. }
  1306. if pty, ok := container.ptyMaster.(*os.File); ok {
  1307. return pty, nil
  1308. }
  1309. return nil, ErrNotATTY
  1310. }