container.go 41 KB

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