container.go 40 KB

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