container.go 38 KB

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