container.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  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/mount"
  10. "github.com/dotcloud/docker/pkg/term"
  11. "github.com/dotcloud/docker/utils"
  12. "github.com/kr/pty"
  13. "io"
  14. "io/ioutil"
  15. "log"
  16. "net"
  17. "os"
  18. "path"
  19. "strconv"
  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) generateLXCConfig() error {
  264. fo, err := os.Create(container.lxcConfigPath())
  265. if err != nil {
  266. return err
  267. }
  268. defer fo.Close()
  269. return LxcTemplateCompiled.Execute(fo, container)
  270. }
  271. func (container *Container) startPty() error {
  272. ptyMaster, ptySlave, err := pty.Open()
  273. if err != nil {
  274. return err
  275. }
  276. container.ptyMaster = ptyMaster
  277. container.process.Stdout = ptySlave
  278. container.process.Stderr = ptySlave
  279. // Copy the PTYs to our broadcasters
  280. go func() {
  281. defer container.stdout.CloseWriters()
  282. utils.Debugf("startPty: begin of stdout pipe")
  283. io.Copy(container.stdout, ptyMaster)
  284. utils.Debugf("startPty: end of stdout pipe")
  285. }()
  286. // stdin
  287. if container.Config.OpenStdin {
  288. container.process.Stdin = ptySlave
  289. go func() {
  290. defer container.stdin.Close()
  291. utils.Debugf("startPty: begin of stdin pipe")
  292. io.Copy(ptyMaster, container.stdin)
  293. utils.Debugf("startPty: end of stdin pipe")
  294. }()
  295. }
  296. if err := container.runtime.execDriver.Start(container.process); err != nil {
  297. return err
  298. }
  299. ptySlave.Close()
  300. return nil
  301. }
  302. func (container *Container) start() error {
  303. container.process.Stdout = container.stdout
  304. container.process.Stderr = container.stderr
  305. if container.Config.OpenStdin {
  306. stdin, err := container.process.StdinPipe()
  307. if err != nil {
  308. return err
  309. }
  310. go func() {
  311. defer stdin.Close()
  312. utils.Debugf("start: begin of stdin pipe")
  313. io.Copy(stdin, container.stdin)
  314. utils.Debugf("start: end of stdin pipe")
  315. }()
  316. }
  317. return container.runtime.execDriver.Start(container.process)
  318. }
  319. func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error {
  320. var cStdout, cStderr io.ReadCloser
  321. var nJobs int
  322. errors := make(chan error, 3)
  323. if stdin != nil && container.Config.OpenStdin {
  324. nJobs += 1
  325. if cStdin, err := container.StdinPipe(); err != nil {
  326. errors <- err
  327. } else {
  328. go func() {
  329. utils.Debugf("attach: stdin: begin")
  330. defer utils.Debugf("attach: stdin: end")
  331. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  332. if container.Config.StdinOnce && !container.Config.Tty {
  333. defer cStdin.Close()
  334. } else {
  335. if cStdout != nil {
  336. defer cStdout.Close()
  337. }
  338. if cStderr != nil {
  339. defer cStderr.Close()
  340. }
  341. }
  342. if container.Config.Tty {
  343. _, err = utils.CopyEscapable(cStdin, stdin)
  344. } else {
  345. _, err = io.Copy(cStdin, stdin)
  346. }
  347. if err == io.ErrClosedPipe {
  348. err = nil
  349. }
  350. if err != nil {
  351. utils.Errorf("attach: stdin: %s", err)
  352. }
  353. errors <- err
  354. }()
  355. }
  356. }
  357. if stdout != nil {
  358. nJobs += 1
  359. if p, err := container.StdoutPipe(); err != nil {
  360. errors <- err
  361. } else {
  362. cStdout = p
  363. go func() {
  364. utils.Debugf("attach: stdout: begin")
  365. defer utils.Debugf("attach: stdout: end")
  366. // If we are in StdinOnce mode, then close stdin
  367. if container.Config.StdinOnce && stdin != nil {
  368. defer stdin.Close()
  369. }
  370. if stdinCloser != nil {
  371. defer stdinCloser.Close()
  372. }
  373. _, err := io.Copy(stdout, cStdout)
  374. if err == io.ErrClosedPipe {
  375. err = nil
  376. }
  377. if err != nil {
  378. utils.Errorf("attach: stdout: %s", err)
  379. }
  380. errors <- err
  381. }()
  382. }
  383. } else {
  384. go func() {
  385. if stdinCloser != nil {
  386. defer stdinCloser.Close()
  387. }
  388. if cStdout, err := container.StdoutPipe(); err != nil {
  389. utils.Errorf("attach: stdout pipe: %s", err)
  390. } else {
  391. io.Copy(&utils.NopWriter{}, cStdout)
  392. }
  393. }()
  394. }
  395. if stderr != nil {
  396. nJobs += 1
  397. if p, err := container.StderrPipe(); err != nil {
  398. errors <- err
  399. } else {
  400. cStderr = p
  401. go func() {
  402. utils.Debugf("attach: stderr: begin")
  403. defer utils.Debugf("attach: stderr: end")
  404. // If we are in StdinOnce mode, then close stdin
  405. if container.Config.StdinOnce && stdin != nil {
  406. defer stdin.Close()
  407. }
  408. if stdinCloser != nil {
  409. defer stdinCloser.Close()
  410. }
  411. _, err := io.Copy(stderr, cStderr)
  412. if err == io.ErrClosedPipe {
  413. err = nil
  414. }
  415. if err != nil {
  416. utils.Errorf("attach: stderr: %s", err)
  417. }
  418. errors <- err
  419. }()
  420. }
  421. } else {
  422. go func() {
  423. if stdinCloser != nil {
  424. defer stdinCloser.Close()
  425. }
  426. if cStderr, err := container.StderrPipe(); err != nil {
  427. utils.Errorf("attach: stdout pipe: %s", err)
  428. } else {
  429. io.Copy(&utils.NopWriter{}, cStderr)
  430. }
  431. }()
  432. }
  433. return utils.Go(func() error {
  434. if cStdout != nil {
  435. defer cStdout.Close()
  436. }
  437. if cStderr != nil {
  438. defer cStderr.Close()
  439. }
  440. // FIXME: how to clean up the stdin goroutine without the unwanted side effect
  441. // of closing the passed stdin? Add an intermediary io.Pipe?
  442. for i := 0; i < nJobs; i += 1 {
  443. utils.Debugf("attach: waiting for job %d/%d", i+1, nJobs)
  444. if err := <-errors; err != nil {
  445. utils.Errorf("attach: job %d returned error %s, aborting all jobs", i+1, err)
  446. return err
  447. }
  448. utils.Debugf("attach: job %d completed successfully", i+1)
  449. }
  450. utils.Debugf("attach: all jobs completed successfully")
  451. return nil
  452. })
  453. }
  454. func (container *Container) Start() (err error) {
  455. container.Lock()
  456. defer container.Unlock()
  457. if container.State.IsRunning() {
  458. return fmt.Errorf("The container %s is already running.", container.ID)
  459. }
  460. defer func() {
  461. if err != nil {
  462. container.cleanup()
  463. }
  464. }()
  465. if err := container.EnsureMounted(); err != nil {
  466. return err
  467. }
  468. if container.runtime.networkManager.disabled {
  469. container.Config.NetworkDisabled = true
  470. container.buildHostnameAndHostsFiles("127.0.1.1")
  471. } else {
  472. if err := container.allocateNetwork(); err != nil {
  473. return err
  474. }
  475. container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  476. }
  477. // Make sure the config is compatible with the current kernel
  478. if container.Config.Memory > 0 && !container.runtime.capabilities.MemoryLimit {
  479. log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  480. container.Config.Memory = 0
  481. }
  482. if container.Config.Memory > 0 && !container.runtime.capabilities.SwapLimit {
  483. log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  484. container.Config.MemorySwap = -1
  485. }
  486. if container.runtime.capabilities.IPv4ForwardingDisabled {
  487. log.Printf("WARNING: IPv4 forwarding is disabled. Networking will not work")
  488. }
  489. if container.Volumes == nil || len(container.Volumes) == 0 {
  490. container.Volumes = make(map[string]string)
  491. container.VolumesRW = make(map[string]bool)
  492. }
  493. // Apply volumes from another container if requested
  494. if err := container.applyExternalVolumes(); err != nil {
  495. return err
  496. }
  497. if err := container.createVolumes(); err != nil {
  498. return err
  499. }
  500. if err := container.generateLXCConfig(); err != nil {
  501. return err
  502. }
  503. var lxcStart string = "lxc-start"
  504. if container.hostConfig.Privileged && container.runtime.capabilities.AppArmor {
  505. lxcStart = path.Join(container.runtime.config.Root, "lxc-start-unconfined")
  506. }
  507. params := []string{
  508. lxcStart,
  509. "-n", container.ID,
  510. "-f", container.lxcConfigPath(),
  511. "--",
  512. "/.dockerinit",
  513. }
  514. // Networking
  515. if !container.Config.NetworkDisabled {
  516. network := container.NetworkSettings
  517. params = append(params,
  518. "-g", network.Gateway,
  519. "-i", fmt.Sprintf("%s/%d", network.IPAddress, network.IPPrefixLen),
  520. "-mtu", strconv.Itoa(container.runtime.config.Mtu),
  521. )
  522. }
  523. // User
  524. if container.Config.User != "" {
  525. params = append(params, "-u", container.Config.User)
  526. }
  527. // Setup environment
  528. env := []string{
  529. "HOME=/",
  530. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  531. "HOSTNAME=" + container.Config.Hostname,
  532. }
  533. if container.Config.Tty {
  534. env = append(env, "TERM=xterm")
  535. }
  536. if container.hostConfig.Privileged {
  537. params = append(params, "-privileged")
  538. }
  539. // Init any links between the parent and children
  540. runtime := container.runtime
  541. children, err := runtime.Children(container.Name)
  542. if err != nil {
  543. return err
  544. }
  545. if len(children) > 0 {
  546. container.activeLinks = make(map[string]*Link, len(children))
  547. // If we encounter an error make sure that we rollback any network
  548. // config and ip table changes
  549. rollback := func() {
  550. for _, link := range container.activeLinks {
  551. link.Disable()
  552. }
  553. container.activeLinks = nil
  554. }
  555. for p, child := range children {
  556. link, err := NewLink(container, child, p, runtime.networkManager.bridgeIface)
  557. if err != nil {
  558. rollback()
  559. return err
  560. }
  561. container.activeLinks[link.Alias()] = link
  562. if err := link.Enable(); err != nil {
  563. rollback()
  564. return err
  565. }
  566. for _, envVar := range link.ToEnv() {
  567. env = append(env, envVar)
  568. }
  569. }
  570. }
  571. for _, elem := range container.Config.Env {
  572. env = append(env, elem)
  573. }
  574. if err := container.generateEnvConfig(env); err != nil {
  575. return err
  576. }
  577. var workingDir string
  578. if container.Config.WorkingDir != "" {
  579. workingDir = path.Clean(container.Config.WorkingDir)
  580. utils.Debugf("[working dir] working dir is %s", workingDir)
  581. if err := os.MkdirAll(path.Join(container.RootfsPath(), workingDir), 0755); err != nil {
  582. return nil
  583. }
  584. params = append(params,
  585. "-w", workingDir,
  586. )
  587. }
  588. // Program
  589. params = append(params, "--", container.Path)
  590. params = append(params, container.Args...)
  591. if RootIsShared() {
  592. // lxc-start really needs / to be non-shared, or all kinds of stuff break
  593. // when lxc-start unmount things and those unmounts propagate to the main
  594. // mount namespace.
  595. // What we really want is to clone into a new namespace and then
  596. // mount / MS_REC|MS_SLAVE, but since we can't really clone or fork
  597. // without exec in go we have to do this horrible shell hack...
  598. shellString :=
  599. "mount --make-rslave /; exec " +
  600. utils.ShellQuoteArguments(params)
  601. params = []string{
  602. "unshare", "-m", "--", "/bin/sh", "-c", shellString,
  603. }
  604. }
  605. root := container.RootfsPath()
  606. envPath, err := container.EnvConfigPath()
  607. if err != nil {
  608. return err
  609. }
  610. // Mount docker specific files into the containers root fs
  611. if err := mount.Mount(runtime.sysInitPath, path.Join(root, "/.dockerinit"), "none", "bind,ro"); err != nil {
  612. return err
  613. }
  614. if err := mount.Mount(envPath, path.Join(root, "/.dockerenv"), "none", "bind,ro"); err != nil {
  615. return err
  616. }
  617. if err := mount.Mount(container.ResolvConfPath, path.Join(root, "/etc/resolv.conf"), "none", "bind,ro"); err != nil {
  618. return err
  619. }
  620. if container.HostnamePath != "" && container.HostsPath != "" {
  621. if err := mount.Mount(container.HostnamePath, path.Join(root, "/etc/hostname"), "none", "bind,ro"); err != nil {
  622. return err
  623. }
  624. if err := mount.Mount(container.HostsPath, path.Join(root, "/etc/hosts"), "none", "bind,ro"); err != nil {
  625. return err
  626. }
  627. }
  628. // Mount user specified volumes
  629. for r, v := range container.Volumes {
  630. mountAs := "ro"
  631. if container.VolumesRW[r] {
  632. mountAs = "rw"
  633. }
  634. if err := mount.Mount(v, path.Join(root, r), "none", fmt.Sprintf("bind,%s", mountAs)); err != nil {
  635. return err
  636. }
  637. }
  638. var en *execdriver.Network
  639. if !container.runtime.networkManager.disabled {
  640. network := container.NetworkSettings
  641. en = &execdriver.Network{
  642. Gateway: network.Gateway,
  643. IPAddress: network.IPAddress,
  644. IPPrefixLen: network.IPPrefixLen,
  645. Mtu: container.runtime.config.Mtu,
  646. }
  647. }
  648. container.process = &execdriver.Process{
  649. Name: container.ID,
  650. Privileged: container.hostConfig.Privileged,
  651. Rootfs: root,
  652. InitPath: "/.dockerinit",
  653. Entrypoint: container.Path,
  654. Arguments: container.Args,
  655. WorkingDir: workingDir,
  656. ConfigPath: container.lxcConfigPath(),
  657. Network: en,
  658. Tty: container.Config.Tty,
  659. User: container.Config.User,
  660. }
  661. // Setup logging of stdout and stderr to disk
  662. if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil {
  663. return err
  664. }
  665. if err := container.runtime.LogToDisk(container.stderr, container.logPath("json"), "stderr"); err != nil {
  666. return err
  667. }
  668. if container.Config.Tty {
  669. err = container.startPty()
  670. } else {
  671. err = container.start()
  672. }
  673. if err != nil {
  674. return err
  675. }
  676. container.State.SetRunning(container.process.Pid())
  677. // Init the lock
  678. container.waitLock = make(chan struct{})
  679. container.ToDisk()
  680. go container.monitor()
  681. return nil
  682. }
  683. func (container *Container) getBindMap() (map[string]BindMap, error) {
  684. // Create the requested bind mounts
  685. binds := make(map[string]BindMap)
  686. // Define illegal container destinations
  687. illegalDsts := []string{"/", "."}
  688. for _, bind := range container.hostConfig.Binds {
  689. // FIXME: factorize bind parsing in parseBind
  690. var src, dst, mode string
  691. arr := strings.Split(bind, ":")
  692. if len(arr) == 2 {
  693. src = arr[0]
  694. dst = arr[1]
  695. mode = "rw"
  696. } else if len(arr) == 3 {
  697. src = arr[0]
  698. dst = arr[1]
  699. mode = arr[2]
  700. } else {
  701. return nil, fmt.Errorf("Invalid bind specification: %s", bind)
  702. }
  703. // Bail if trying to mount to an illegal destination
  704. for _, illegal := range illegalDsts {
  705. if dst == illegal {
  706. return nil, fmt.Errorf("Illegal bind destination: %s", dst)
  707. }
  708. }
  709. bindMap := BindMap{
  710. SrcPath: src,
  711. DstPath: dst,
  712. Mode: mode,
  713. }
  714. binds[path.Clean(dst)] = bindMap
  715. }
  716. return binds, nil
  717. }
  718. func (container *Container) createVolumes() error {
  719. binds, err := container.getBindMap()
  720. if err != nil {
  721. return err
  722. }
  723. volumesDriver := container.runtime.volumes.driver
  724. // Create the requested volumes if they don't exist
  725. for volPath := range container.Config.Volumes {
  726. volPath = path.Clean(volPath)
  727. volIsDir := true
  728. // Skip existing volumes
  729. if _, exists := container.Volumes[volPath]; exists {
  730. continue
  731. }
  732. var srcPath string
  733. var isBindMount bool
  734. srcRW := false
  735. // If an external bind is defined for this volume, use that as a source
  736. if bindMap, exists := binds[volPath]; exists {
  737. isBindMount = true
  738. srcPath = bindMap.SrcPath
  739. if strings.ToLower(bindMap.Mode) == "rw" {
  740. srcRW = true
  741. }
  742. if stat, err := os.Lstat(bindMap.SrcPath); err != nil {
  743. return err
  744. } else {
  745. volIsDir = stat.IsDir()
  746. }
  747. // Otherwise create an directory in $ROOT/volumes/ and use that
  748. } else {
  749. // Do not pass a container as the parameter for the volume creation.
  750. // The graph driver using the container's information ( Image ) to
  751. // create the parent.
  752. c, err := container.runtime.volumes.Create(nil, nil, "", "", nil)
  753. if err != nil {
  754. return err
  755. }
  756. srcPath, err = volumesDriver.Get(c.ID)
  757. if err != nil {
  758. return fmt.Errorf("Driver %s failed to get volume rootfs %s: %s", volumesDriver, c.ID, err)
  759. }
  760. srcRW = true // RW by default
  761. }
  762. container.Volumes[volPath] = srcPath
  763. container.VolumesRW[volPath] = srcRW
  764. // Create the mountpoint
  765. volPath = path.Join(container.RootfsPath(), volPath)
  766. rootVolPath, err := utils.FollowSymlinkInScope(volPath, container.RootfsPath())
  767. if err != nil {
  768. return err
  769. }
  770. if _, err := os.Stat(rootVolPath); err != nil {
  771. if os.IsNotExist(err) {
  772. if volIsDir {
  773. if err := os.MkdirAll(rootVolPath, 0755); err != nil {
  774. return err
  775. }
  776. } else {
  777. if err := os.MkdirAll(path.Dir(rootVolPath), 0755); err != nil {
  778. return err
  779. }
  780. if f, err := os.OpenFile(rootVolPath, os.O_CREATE, 0755); err != nil {
  781. return err
  782. } else {
  783. f.Close()
  784. }
  785. }
  786. }
  787. }
  788. // Do not copy or change permissions if we are mounting from the host
  789. if srcRW && !isBindMount {
  790. volList, err := ioutil.ReadDir(rootVolPath)
  791. if err != nil {
  792. return err
  793. }
  794. if len(volList) > 0 {
  795. srcList, err := ioutil.ReadDir(srcPath)
  796. if err != nil {
  797. return err
  798. }
  799. if len(srcList) == 0 {
  800. // If the source volume is empty copy files from the root into the volume
  801. if err := archive.CopyWithTar(rootVolPath, srcPath); err != nil {
  802. return err
  803. }
  804. var stat syscall.Stat_t
  805. if err := syscall.Stat(rootVolPath, &stat); err != nil {
  806. return err
  807. }
  808. var srcStat syscall.Stat_t
  809. if err := syscall.Stat(srcPath, &srcStat); err != nil {
  810. return err
  811. }
  812. // Change the source volume's ownership if it differs from the root
  813. // files that where just copied
  814. if stat.Uid != srcStat.Uid || stat.Gid != srcStat.Gid {
  815. if err := os.Chown(srcPath, int(stat.Uid), int(stat.Gid)); err != nil {
  816. return err
  817. }
  818. }
  819. }
  820. }
  821. }
  822. }
  823. return nil
  824. }
  825. func (container *Container) applyExternalVolumes() error {
  826. if container.Config.VolumesFrom != "" {
  827. containerSpecs := strings.Split(container.Config.VolumesFrom, ",")
  828. for _, containerSpec := range containerSpecs {
  829. mountRW := true
  830. specParts := strings.SplitN(containerSpec, ":", 2)
  831. switch len(specParts) {
  832. case 0:
  833. return fmt.Errorf("Malformed volumes-from specification: %s", container.Config.VolumesFrom)
  834. case 2:
  835. switch specParts[1] {
  836. case "ro":
  837. mountRW = false
  838. case "rw": // mountRW is already true
  839. default:
  840. return fmt.Errorf("Malformed volumes-from speficication: %s", containerSpec)
  841. }
  842. }
  843. c := container.runtime.Get(specParts[0])
  844. if c == nil {
  845. return fmt.Errorf("Container %s not found. Impossible to mount its volumes", container.ID)
  846. }
  847. for volPath, id := range c.Volumes {
  848. if _, exists := container.Volumes[volPath]; exists {
  849. continue
  850. }
  851. if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil {
  852. return err
  853. }
  854. container.Volumes[volPath] = id
  855. if isRW, exists := c.VolumesRW[volPath]; exists {
  856. container.VolumesRW[volPath] = isRW && mountRW
  857. }
  858. }
  859. }
  860. }
  861. return nil
  862. }
  863. func (container *Container) Run() error {
  864. if err := container.Start(); err != nil {
  865. return err
  866. }
  867. container.Wait()
  868. return nil
  869. }
  870. func (container *Container) Output() (output []byte, err error) {
  871. pipe, err := container.StdoutPipe()
  872. if err != nil {
  873. return nil, err
  874. }
  875. defer pipe.Close()
  876. if err := container.Start(); err != nil {
  877. return nil, err
  878. }
  879. output, err = ioutil.ReadAll(pipe)
  880. container.Wait()
  881. return output, err
  882. }
  883. // Container.StdinPipe returns a WriteCloser which can be used to feed data
  884. // to the standard input of the container's active process.
  885. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser
  886. // which can be used to retrieve the standard output (and error) generated
  887. // by the container's active process. The output (and error) are actually
  888. // copied and delivered to all StdoutPipe and StderrPipe consumers, using
  889. // a kind of "broadcaster".
  890. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  891. return container.stdinPipe, nil
  892. }
  893. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  894. reader, writer := io.Pipe()
  895. container.stdout.AddWriter(writer, "")
  896. return utils.NewBufReader(reader), nil
  897. }
  898. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  899. reader, writer := io.Pipe()
  900. container.stderr.AddWriter(writer, "")
  901. return utils.NewBufReader(reader), nil
  902. }
  903. func (container *Container) buildHostnameAndHostsFiles(IP string) {
  904. container.HostnamePath = path.Join(container.root, "hostname")
  905. ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  906. hostsContent := []byte(`
  907. 127.0.0.1 localhost
  908. ::1 localhost ip6-localhost ip6-loopback
  909. fe00::0 ip6-localnet
  910. ff00::0 ip6-mcastprefix
  911. ff02::1 ip6-allnodes
  912. ff02::2 ip6-allrouters
  913. `)
  914. container.HostsPath = path.Join(container.root, "hosts")
  915. if container.Config.Domainname != "" {
  916. hostsContent = append([]byte(fmt.Sprintf("%s\t%s.%s %s\n", IP, container.Config.Hostname, container.Config.Domainname, container.Config.Hostname)), hostsContent...)
  917. } else if !container.Config.NetworkDisabled {
  918. hostsContent = append([]byte(fmt.Sprintf("%s\t%s\n", IP, container.Config.Hostname)), hostsContent...)
  919. }
  920. ioutil.WriteFile(container.HostsPath, hostsContent, 0644)
  921. }
  922. func (container *Container) allocateNetwork() error {
  923. if container.Config.NetworkDisabled {
  924. return nil
  925. }
  926. var (
  927. iface *NetworkInterface
  928. err error
  929. )
  930. if container.State.IsGhost() {
  931. if manager := container.runtime.networkManager; manager.disabled {
  932. iface = &NetworkInterface{disabled: true}
  933. } else {
  934. iface = &NetworkInterface{
  935. IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask},
  936. Gateway: manager.bridgeNetwork.IP,
  937. manager: manager,
  938. }
  939. if iface != nil && iface.IPNet.IP != nil {
  940. ipNum := ipToInt(iface.IPNet.IP)
  941. manager.ipAllocator.inUse[ipNum] = struct{}{}
  942. } else {
  943. iface, err = container.runtime.networkManager.Allocate()
  944. if err != nil {
  945. return err
  946. }
  947. }
  948. }
  949. } else {
  950. iface, err = container.runtime.networkManager.Allocate()
  951. if err != nil {
  952. return err
  953. }
  954. }
  955. if container.Config.PortSpecs != nil {
  956. utils.Debugf("Migrating port mappings for container: %s", strings.Join(container.Config.PortSpecs, ", "))
  957. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  958. return err
  959. }
  960. container.Config.PortSpecs = nil
  961. if err := container.writeHostConfig(); err != nil {
  962. return err
  963. }
  964. }
  965. var (
  966. portSpecs = make(map[Port]struct{})
  967. bindings = make(map[Port][]PortBinding)
  968. )
  969. if !container.State.IsGhost() {
  970. if container.Config.ExposedPorts != nil {
  971. portSpecs = container.Config.ExposedPorts
  972. }
  973. if container.hostConfig.PortBindings != nil {
  974. bindings = container.hostConfig.PortBindings
  975. }
  976. } else {
  977. if container.NetworkSettings.Ports != nil {
  978. for port, binding := range container.NetworkSettings.Ports {
  979. portSpecs[port] = struct{}{}
  980. bindings[port] = binding
  981. }
  982. }
  983. }
  984. container.NetworkSettings.PortMapping = nil
  985. for port := range portSpecs {
  986. binding := bindings[port]
  987. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  988. binding = append(binding, PortBinding{})
  989. }
  990. for i := 0; i < len(binding); i++ {
  991. b := binding[i]
  992. nat, err := iface.AllocatePort(port, b)
  993. if err != nil {
  994. iface.Release()
  995. return err
  996. }
  997. utils.Debugf("Allocate port: %s:%s->%s", nat.Binding.HostIp, port, nat.Binding.HostPort)
  998. binding[i] = nat.Binding
  999. }
  1000. bindings[port] = binding
  1001. }
  1002. container.writeHostConfig()
  1003. container.NetworkSettings.Ports = bindings
  1004. container.network = iface
  1005. container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface
  1006. container.NetworkSettings.IPAddress = iface.IPNet.IP.String()
  1007. container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size()
  1008. container.NetworkSettings.Gateway = iface.Gateway.String()
  1009. return nil
  1010. }
  1011. func (container *Container) releaseNetwork() {
  1012. if container.Config.NetworkDisabled || container.network == nil {
  1013. return
  1014. }
  1015. container.network.Release()
  1016. container.network = nil
  1017. container.NetworkSettings = &NetworkSettings{}
  1018. }
  1019. func (container *Container) monitor() {
  1020. // Wait for the program to exit
  1021. if container.process == nil {
  1022. panic("Container process is nil")
  1023. }
  1024. if err := container.runtime.execDriver.Wait(container.process, time.Duration(0)); err != nil {
  1025. // Since non-zero exit status and signal terminations will cause err to be non-nil,
  1026. // we have to actually discard it. Still, log it anyway, just in case.
  1027. utils.Debugf("monitor: cmd.Wait reported exit status %s for container %s", err, container.ID)
  1028. if container.runtime != nil && container.runtime.srv != nil {
  1029. container.runtime.srv.LogEvent("die", container.ID, container.runtime.repositories.ImageName(container.Image))
  1030. }
  1031. }
  1032. // Cleanup
  1033. container.cleanup()
  1034. // Re-create a brand new stdin pipe once the container exited
  1035. if container.Config.OpenStdin {
  1036. container.stdin, container.stdinPipe = io.Pipe()
  1037. }
  1038. exitCode := container.process.GetExitCode()
  1039. container.State.SetStopped(exitCode)
  1040. // Release the lock
  1041. close(container.waitLock)
  1042. if err := container.ToDisk(); err != nil {
  1043. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  1044. // If another goroutine was waiting for Wait() to return before removing the container's root
  1045. // from the filesystem... At this point it may already have done so.
  1046. // This is because State.setStopped() has already been called, and has caused Wait()
  1047. // to return.
  1048. // FIXME: why are we serializing running state to disk in the first place?
  1049. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
  1050. }
  1051. }
  1052. func (container *Container) cleanup() {
  1053. container.releaseNetwork()
  1054. // Disable all active links
  1055. if container.activeLinks != nil {
  1056. for _, link := range container.activeLinks {
  1057. link.Disable()
  1058. }
  1059. }
  1060. if container.Config.OpenStdin {
  1061. if err := container.stdin.Close(); err != nil {
  1062. utils.Errorf("%s: Error close stdin: %s", container.ID, err)
  1063. }
  1064. }
  1065. if err := container.stdout.CloseWriters(); err != nil {
  1066. utils.Errorf("%s: Error close stdout: %s", container.ID, err)
  1067. }
  1068. if err := container.stderr.CloseWriters(); err != nil {
  1069. utils.Errorf("%s: Error close stderr: %s", container.ID, err)
  1070. }
  1071. if container.ptyMaster != nil {
  1072. if err := container.ptyMaster.Close(); err != nil {
  1073. utils.Errorf("%s: Error closing Pty master: %s", container.ID, err)
  1074. }
  1075. }
  1076. if err := container.Unmount(); err != nil {
  1077. log.Printf("%v: Failed to umount filesystem: %v", container.ID, err)
  1078. }
  1079. }
  1080. func (container *Container) kill(sig int) error {
  1081. container.Lock()
  1082. defer container.Unlock()
  1083. if !container.State.IsRunning() {
  1084. return nil
  1085. }
  1086. return container.runtime.execDriver.Kill(container.process, sig)
  1087. }
  1088. func (container *Container) Kill() error {
  1089. if !container.State.IsRunning() {
  1090. return nil
  1091. }
  1092. // 1. Send SIGKILL
  1093. if err := container.kill(9); err != nil {
  1094. return err
  1095. }
  1096. // 2. Wait for the process to die, in last resort, try to kill the process directly
  1097. if err := container.WaitTimeout(10 * time.Second); err != nil {
  1098. if container.process == nil {
  1099. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", utils.TruncateID(container.ID))
  1100. }
  1101. log.Printf("Container %s failed to exit within 10 seconds of lxc-kill %s - trying direct SIGKILL", "SIGKILL", utils.TruncateID(container.ID))
  1102. if err := container.runtime.execDriver.Kill(container.process, 9); err != nil {
  1103. return err
  1104. }
  1105. }
  1106. container.Wait()
  1107. return nil
  1108. }
  1109. func (container *Container) Stop(seconds int) error {
  1110. if !container.State.IsRunning() {
  1111. return nil
  1112. }
  1113. // 1. Send a SIGTERM
  1114. if err := container.kill(15); err != nil {
  1115. utils.Debugf("Error sending kill SIGTERM: %s", err)
  1116. log.Print("Failed to send SIGTERM to the process, force killing")
  1117. if err := container.kill(9); err != nil {
  1118. return err
  1119. }
  1120. }
  1121. // 2. Wait for the process to exit on its own
  1122. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  1123. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  1124. // 3. If it doesn't, then send SIGKILL
  1125. if err := container.Kill(); err != nil {
  1126. return err
  1127. }
  1128. }
  1129. return nil
  1130. }
  1131. func (container *Container) Restart(seconds int) error {
  1132. if err := container.Stop(seconds); err != nil {
  1133. return err
  1134. }
  1135. return container.Start()
  1136. }
  1137. // Wait blocks until the container stops running, then returns its exit code.
  1138. func (container *Container) Wait() int {
  1139. <-container.waitLock
  1140. return container.State.GetExitCode()
  1141. }
  1142. func (container *Container) Resize(h, w int) error {
  1143. pty, ok := container.ptyMaster.(*os.File)
  1144. if !ok {
  1145. return fmt.Errorf("ptyMaster does not have Fd() method")
  1146. }
  1147. return term.SetWinsize(pty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  1148. }
  1149. func (container *Container) ExportRw() (archive.Archive, error) {
  1150. if err := container.EnsureMounted(); err != nil {
  1151. return nil, err
  1152. }
  1153. if container.runtime == nil {
  1154. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  1155. }
  1156. return container.runtime.Diff(container)
  1157. }
  1158. func (container *Container) Export() (archive.Archive, error) {
  1159. if err := container.EnsureMounted(); err != nil {
  1160. return nil, err
  1161. }
  1162. return archive.Tar(container.RootfsPath(), archive.Uncompressed)
  1163. }
  1164. func (container *Container) WaitTimeout(timeout time.Duration) error {
  1165. done := make(chan bool)
  1166. go func() {
  1167. container.Wait()
  1168. done <- true
  1169. }()
  1170. select {
  1171. case <-time.After(timeout):
  1172. return fmt.Errorf("Timed Out")
  1173. case <-done:
  1174. return nil
  1175. }
  1176. }
  1177. func (container *Container) EnsureMounted() error {
  1178. // FIXME: EnsureMounted is deprecated because drivers are now responsible
  1179. // for re-entrant mounting in their Get() method.
  1180. return container.Mount()
  1181. }
  1182. func (container *Container) Mount() error {
  1183. return container.runtime.Mount(container)
  1184. }
  1185. func (container *Container) Changes() ([]archive.Change, error) {
  1186. return container.runtime.Changes(container)
  1187. }
  1188. func (container *Container) GetImage() (*Image, error) {
  1189. if container.runtime == nil {
  1190. return nil, fmt.Errorf("Can't get image of unregistered container")
  1191. }
  1192. return container.runtime.graph.Get(container.Image)
  1193. }
  1194. func (container *Container) Unmount() error {
  1195. var (
  1196. err error
  1197. root = container.RootfsPath()
  1198. mounts = []string{
  1199. path.Join(root, "/.dockerinit"),
  1200. path.Join(root, "/.dockerenv"),
  1201. path.Join(root, "/etc/resolv.conf"),
  1202. }
  1203. )
  1204. if container.HostnamePath != "" && container.HostsPath != "" {
  1205. mounts = append(mounts, path.Join(root, "/etc/hostname"), path.Join(root, "/etc/hosts"))
  1206. }
  1207. for r := range container.Volumes {
  1208. mounts = append(mounts, path.Join(root, r))
  1209. }
  1210. for _, m := range mounts {
  1211. if lastError := mount.Unmount(m); lastError != nil {
  1212. err = lastError
  1213. }
  1214. }
  1215. if err != nil {
  1216. return err
  1217. }
  1218. return container.runtime.Unmount(container)
  1219. }
  1220. func (container *Container) logPath(name string) string {
  1221. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name))
  1222. }
  1223. func (container *Container) ReadLog(name string) (io.Reader, error) {
  1224. return os.Open(container.logPath(name))
  1225. }
  1226. func (container *Container) hostConfigPath() string {
  1227. return path.Join(container.root, "hostconfig.json")
  1228. }
  1229. func (container *Container) jsonPath() string {
  1230. return path.Join(container.root, "config.json")
  1231. }
  1232. func (container *Container) EnvConfigPath() (string, error) {
  1233. p := path.Join(container.root, "config.env")
  1234. if _, err := os.Stat(p); err != nil {
  1235. if os.IsNotExist(err) {
  1236. f, err := os.Create(p)
  1237. if err != nil {
  1238. return "", err
  1239. }
  1240. f.Close()
  1241. } else {
  1242. return "", err
  1243. }
  1244. }
  1245. return p, nil
  1246. }
  1247. func (container *Container) lxcConfigPath() string {
  1248. return path.Join(container.root, "config.lxc")
  1249. }
  1250. // This method must be exported to be used from the lxc template
  1251. func (container *Container) RootfsPath() string {
  1252. return container.rootfs
  1253. }
  1254. func validateID(id string) error {
  1255. if id == "" {
  1256. return fmt.Errorf("Invalid empty id")
  1257. }
  1258. return nil
  1259. }
  1260. // GetSize, return real size, virtual size
  1261. func (container *Container) GetSize() (int64, int64) {
  1262. var (
  1263. sizeRw, sizeRootfs int64
  1264. err error
  1265. driver = container.runtime.driver
  1266. )
  1267. if err := container.EnsureMounted(); err != nil {
  1268. utils.Errorf("Warning: failed to compute size of container rootfs %s: %s", container.ID, err)
  1269. return sizeRw, sizeRootfs
  1270. }
  1271. if differ, ok := container.runtime.driver.(graphdriver.Differ); ok {
  1272. sizeRw, err = differ.DiffSize(container.ID)
  1273. if err != nil {
  1274. utils.Errorf("Warning: driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  1275. // FIXME: GetSize should return an error. Not changing it now in case
  1276. // there is a side-effect.
  1277. sizeRw = -1
  1278. }
  1279. } else {
  1280. changes, _ := container.Changes()
  1281. if changes != nil {
  1282. sizeRw = archive.ChangesSize(container.RootfsPath(), changes)
  1283. } else {
  1284. sizeRw = -1
  1285. }
  1286. }
  1287. if _, err = os.Stat(container.RootfsPath()); err != nil {
  1288. if sizeRootfs, err = utils.TreeSize(container.RootfsPath()); err != nil {
  1289. sizeRootfs = -1
  1290. }
  1291. }
  1292. return sizeRw, sizeRootfs
  1293. }
  1294. func (container *Container) Copy(resource string) (archive.Archive, error) {
  1295. if err := container.EnsureMounted(); err != nil {
  1296. return nil, err
  1297. }
  1298. var filter []string
  1299. basePath := path.Join(container.RootfsPath(), resource)
  1300. stat, err := os.Stat(basePath)
  1301. if err != nil {
  1302. return nil, err
  1303. }
  1304. if !stat.IsDir() {
  1305. d, f := path.Split(basePath)
  1306. basePath = d
  1307. filter = []string{f}
  1308. } else {
  1309. filter = []string{path.Base(basePath)}
  1310. basePath = path.Dir(basePath)
  1311. }
  1312. return archive.TarFilter(basePath, &archive.TarOptions{
  1313. Compression: archive.Uncompressed,
  1314. Includes: filter,
  1315. Recursive: true,
  1316. })
  1317. }
  1318. // Returns true if the container exposes a certain port
  1319. func (container *Container) Exposes(p Port) bool {
  1320. _, exists := container.Config.ExposedPorts[p]
  1321. return exists
  1322. }
  1323. func (container *Container) GetPtyMaster() (*os.File, error) {
  1324. if container.ptyMaster == nil {
  1325. return nil, ErrNoTTY
  1326. }
  1327. if pty, ok := container.ptyMaster.(*os.File); ok {
  1328. return pty, nil
  1329. }
  1330. return nil, ErrNotATTY
  1331. }