container.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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. manager := container.runtime.networkManager
  945. if manager.disabled {
  946. iface = &NetworkInterface{disabled: true}
  947. } else {
  948. iface = &NetworkInterface{
  949. IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask},
  950. Gateway: manager.bridgeNetwork.IP,
  951. manager: manager,
  952. }
  953. if iface !=nil && iface.IPNet.IP != nil {
  954. ipNum := ipToInt(iface.IPNet.IP)
  955. manager.ipAllocator.inUse[ipNum] = struct{}{}
  956. } else {
  957. iface, err = container.runtime.networkManager.Allocate()
  958. if err != nil {
  959. return err
  960. }
  961. }
  962. }
  963. } else {
  964. iface, err = container.runtime.networkManager.Allocate()
  965. if err != nil {
  966. return err
  967. }
  968. }
  969. if container.Config.PortSpecs != nil {
  970. utils.Debugf("Migrating port mappings for container: %s", strings.Join(container.Config.PortSpecs, ", "))
  971. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  972. return err
  973. }
  974. container.Config.PortSpecs = nil
  975. if err := container.writeHostConfig(); err != nil {
  976. return err
  977. }
  978. }
  979. portSpecs := make(map[Port]struct{})
  980. bindings := make(map[Port][]PortBinding)
  981. if !container.State.Ghost {
  982. if container.Config.ExposedPorts != nil {
  983. portSpecs = container.Config.ExposedPorts
  984. }
  985. if container.hostConfig.PortBindings != nil {
  986. bindings = container.hostConfig.PortBindings
  987. }
  988. } else {
  989. if container.NetworkSettings.Ports != nil {
  990. for port, binding := range container.NetworkSettings.Ports {
  991. portSpecs[port] = struct{}{}
  992. bindings[port] = binding
  993. }
  994. }
  995. }
  996. container.NetworkSettings.PortMapping = nil
  997. for port := range portSpecs {
  998. binding := bindings[port]
  999. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  1000. binding = append(binding, PortBinding{})
  1001. }
  1002. for i := 0; i < len(binding); i++ {
  1003. b := binding[i]
  1004. nat, err := iface.AllocatePort(port, b)
  1005. if err != nil {
  1006. iface.Release()
  1007. return err
  1008. }
  1009. utils.Debugf("Allocate port: %s:%s->%s", nat.Binding.HostIp, port, nat.Binding.HostPort)
  1010. binding[i] = nat.Binding
  1011. }
  1012. bindings[port] = binding
  1013. }
  1014. container.writeHostConfig()
  1015. container.NetworkSettings.Ports = bindings
  1016. container.network = iface
  1017. container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface
  1018. container.NetworkSettings.IPAddress = iface.IPNet.IP.String()
  1019. container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size()
  1020. container.NetworkSettings.Gateway = iface.Gateway.String()
  1021. return nil
  1022. }
  1023. func (container *Container) releaseNetwork() {
  1024. if container.Config.NetworkDisabled || container.network == nil {
  1025. return
  1026. }
  1027. container.network.Release()
  1028. container.network = nil
  1029. container.NetworkSettings = &NetworkSettings{}
  1030. }
  1031. // FIXME: replace this with a control socket within dockerinit
  1032. func (container *Container) waitLxc() error {
  1033. for {
  1034. output, err := exec.Command("lxc-info", "-n", container.ID).CombinedOutput()
  1035. if err != nil {
  1036. return err
  1037. }
  1038. if !strings.Contains(string(output), "RUNNING") {
  1039. return nil
  1040. }
  1041. time.Sleep(500 * time.Millisecond)
  1042. }
  1043. }
  1044. func (container *Container) monitor() {
  1045. // Wait for the program to exit
  1046. // If the command does not exist, try to wait via lxc
  1047. // (This probably happens only for ghost containers, i.e. containers that were running when Docker started)
  1048. if container.cmd == nil {
  1049. utils.Debugf("monitor: waiting for container %s using waitLxc", container.ID)
  1050. if err := container.waitLxc(); err != nil {
  1051. utils.Errorf("monitor: while waiting for container %s, waitLxc had a problem: %s", container.ID, err)
  1052. }
  1053. } else {
  1054. utils.Debugf("monitor: waiting for container %s using cmd.Wait", container.ID)
  1055. if err := container.cmd.Wait(); err != nil {
  1056. // Since non-zero exit status and signal terminations will cause err to be non-nil,
  1057. // we have to actually discard it. Still, log it anyway, just in case.
  1058. utils.Debugf("monitor: cmd.Wait reported exit status %s for container %s", err, container.ID)
  1059. }
  1060. }
  1061. utils.Debugf("monitor: container %s finished", container.ID)
  1062. exitCode := -1
  1063. if container.cmd != nil {
  1064. exitCode = container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
  1065. }
  1066. // Report status back
  1067. container.State.setStopped(exitCode)
  1068. if container.runtime != nil && container.runtime.srv != nil {
  1069. container.runtime.srv.LogEvent("die", container.ShortID(), container.runtime.repositories.ImageName(container.Image))
  1070. }
  1071. // Cleanup
  1072. container.cleanup()
  1073. // Re-create a brand new stdin pipe once the container exited
  1074. if container.Config.OpenStdin {
  1075. container.stdin, container.stdinPipe = io.Pipe()
  1076. }
  1077. // Release the lock
  1078. close(container.waitLock)
  1079. if err := container.ToDisk(); err != nil {
  1080. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  1081. // If another goroutine was waiting for Wait() to return before removing the container's root
  1082. // from the filesystem... At this point it may already have done so.
  1083. // This is because State.setStopped() has already been called, and has caused Wait()
  1084. // to return.
  1085. // FIXME: why are we serializing running state to disk in the first place?
  1086. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
  1087. }
  1088. }
  1089. func (container *Container) cleanup() {
  1090. container.releaseNetwork()
  1091. // Disable all active links
  1092. if container.activeLinks != nil {
  1093. for _, link := range container.activeLinks {
  1094. link.Disable()
  1095. }
  1096. }
  1097. if container.Config.OpenStdin {
  1098. if err := container.stdin.Close(); err != nil {
  1099. utils.Errorf("%s: Error close stdin: %s", container.ID, err)
  1100. }
  1101. }
  1102. if err := container.stdout.CloseWriters(); err != nil {
  1103. utils.Errorf("%s: Error close stdout: %s", container.ID, err)
  1104. }
  1105. if err := container.stderr.CloseWriters(); err != nil {
  1106. utils.Errorf("%s: Error close stderr: %s", container.ID, err)
  1107. }
  1108. if container.ptyMaster != nil {
  1109. if err := container.ptyMaster.Close(); err != nil {
  1110. utils.Errorf("%s: Error closing Pty master: %s", container.ID, err)
  1111. }
  1112. }
  1113. if err := container.Unmount(); err != nil {
  1114. log.Printf("%v: Failed to umount filesystem: %v", container.ID, err)
  1115. }
  1116. }
  1117. func (container *Container) kill(sig int) error {
  1118. container.State.Lock()
  1119. defer container.State.Unlock()
  1120. if !container.State.Running {
  1121. return nil
  1122. }
  1123. if output, err := exec.Command("lxc-kill", "-n", container.ID, strconv.Itoa(sig)).CombinedOutput(); err != nil {
  1124. log.Printf("error killing container %s (%s, %s)", container.ShortID(), output, err)
  1125. return err
  1126. }
  1127. return nil
  1128. }
  1129. func (container *Container) Kill() error {
  1130. if !container.State.Running {
  1131. return nil
  1132. }
  1133. // 1. Send SIGKILL
  1134. if err := container.kill(9); err != nil {
  1135. return err
  1136. }
  1137. // 2. Wait for the process to die, in last resort, try to kill the process directly
  1138. if err := container.WaitTimeout(10 * time.Second); err != nil {
  1139. if container.cmd == nil {
  1140. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", container.ShortID())
  1141. }
  1142. log.Printf("Container %s failed to exit within 10 seconds of lxc-kill %s - trying direct SIGKILL", "SIGKILL", container.ShortID())
  1143. if err := container.cmd.Process.Kill(); err != nil {
  1144. return err
  1145. }
  1146. }
  1147. container.Wait()
  1148. return nil
  1149. }
  1150. func (container *Container) Stop(seconds int) error {
  1151. if !container.State.Running {
  1152. return nil
  1153. }
  1154. // 1. Send a SIGTERM
  1155. if err := container.kill(15); err != nil {
  1156. utils.Debugf("Error sending kill SIGTERM: %s", err)
  1157. log.Print("Failed to send SIGTERM to the process, force killing")
  1158. if err := container.kill(9); err != nil {
  1159. return err
  1160. }
  1161. }
  1162. // 2. Wait for the process to exit on its own
  1163. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  1164. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  1165. // 3. If it doesn't, then send SIGKILL
  1166. if err := container.Kill(); err != nil {
  1167. return err
  1168. }
  1169. }
  1170. return nil
  1171. }
  1172. func (container *Container) Restart(seconds int) error {
  1173. if err := container.Stop(seconds); err != nil {
  1174. return err
  1175. }
  1176. return container.Start()
  1177. }
  1178. // Wait blocks until the container stops running, then returns its exit code.
  1179. func (container *Container) Wait() int {
  1180. <-container.waitLock
  1181. return container.State.ExitCode
  1182. }
  1183. func (container *Container) Resize(h, w int) error {
  1184. pty, ok := container.ptyMaster.(*os.File)
  1185. if !ok {
  1186. return fmt.Errorf("ptyMaster does not have Fd() method")
  1187. }
  1188. return term.SetWinsize(pty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  1189. }
  1190. func (container *Container) ExportRw() (archive.Archive, error) {
  1191. return archive.Tar(container.rwPath(), archive.Uncompressed)
  1192. }
  1193. func (container *Container) RwChecksum() (string, error) {
  1194. rwData, err := archive.Tar(container.rwPath(), archive.Xz)
  1195. if err != nil {
  1196. return "", err
  1197. }
  1198. return utils.HashData(rwData)
  1199. }
  1200. func (container *Container) Export() (archive.Archive, error) {
  1201. if err := container.EnsureMounted(); err != nil {
  1202. return nil, err
  1203. }
  1204. return archive.Tar(container.RootfsPath(), archive.Uncompressed)
  1205. }
  1206. func (container *Container) WaitTimeout(timeout time.Duration) error {
  1207. done := make(chan bool)
  1208. go func() {
  1209. container.Wait()
  1210. done <- true
  1211. }()
  1212. select {
  1213. case <-time.After(timeout):
  1214. return fmt.Errorf("Timed Out")
  1215. case <-done:
  1216. return nil
  1217. }
  1218. }
  1219. func (container *Container) EnsureMounted() error {
  1220. if mounted, err := container.Mounted(); err != nil {
  1221. return err
  1222. } else if mounted {
  1223. return nil
  1224. }
  1225. return container.Mount()
  1226. }
  1227. func (container *Container) Mount() error {
  1228. image, err := container.GetImage()
  1229. if err != nil {
  1230. return err
  1231. }
  1232. return image.Mount(container.RootfsPath(), container.rwPath())
  1233. }
  1234. func (container *Container) Changes() ([]Change, error) {
  1235. image, err := container.GetImage()
  1236. if err != nil {
  1237. return nil, err
  1238. }
  1239. return image.Changes(container.rwPath())
  1240. }
  1241. func (container *Container) GetImage() (*Image, error) {
  1242. if container.runtime == nil {
  1243. return nil, fmt.Errorf("Can't get image of unregistered container")
  1244. }
  1245. return container.runtime.graph.Get(container.Image)
  1246. }
  1247. func (container *Container) Mounted() (bool, error) {
  1248. return Mounted(container.RootfsPath())
  1249. }
  1250. func (container *Container) Unmount() error {
  1251. if _, err := os.Stat(container.RootfsPath()); err != nil {
  1252. if os.IsNotExist(err) {
  1253. return nil
  1254. }
  1255. return err
  1256. }
  1257. return Unmount(container.RootfsPath())
  1258. }
  1259. // ShortID returns a shorthand version of the container's id for convenience.
  1260. // A collision with other container shorthands is very unlikely, but possible.
  1261. // In case of a collision a lookup with Runtime.Get() will fail, and the caller
  1262. // will need to use a langer prefix, or the full-length container Id.
  1263. func (container *Container) ShortID() string {
  1264. return utils.TruncateID(container.ID)
  1265. }
  1266. func (container *Container) logPath(name string) string {
  1267. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name))
  1268. }
  1269. func (container *Container) ReadLog(name string) (io.Reader, error) {
  1270. return os.Open(container.logPath(name))
  1271. }
  1272. func (container *Container) hostConfigPath() string {
  1273. return path.Join(container.root, "hostconfig.json")
  1274. }
  1275. func (container *Container) jsonPath() string {
  1276. return path.Join(container.root, "config.json")
  1277. }
  1278. func (container *Container) EnvConfigPath() string {
  1279. return path.Join(container.root, "config.env")
  1280. }
  1281. func (container *Container) lxcConfigPath() string {
  1282. return path.Join(container.root, "config.lxc")
  1283. }
  1284. // This method must be exported to be used from the lxc template
  1285. func (container *Container) RootfsPath() string {
  1286. return path.Join(container.root, "rootfs")
  1287. }
  1288. func (container *Container) rwPath() string {
  1289. return path.Join(container.root, "rw")
  1290. }
  1291. func validateID(id string) error {
  1292. if id == "" {
  1293. return fmt.Errorf("Invalid empty id")
  1294. }
  1295. return nil
  1296. }
  1297. // GetSize, return real size, virtual size
  1298. func (container *Container) GetSize() (int64, int64) {
  1299. var sizeRw, sizeRootfs int64
  1300. filepath.Walk(container.rwPath(), func(path string, fileInfo os.FileInfo, err error) error {
  1301. if fileInfo != nil {
  1302. sizeRw += fileInfo.Size()
  1303. }
  1304. return nil
  1305. })
  1306. _, err := os.Stat(container.RootfsPath())
  1307. if err == nil {
  1308. filepath.Walk(container.RootfsPath(), func(path string, fileInfo os.FileInfo, err error) error {
  1309. if fileInfo != nil {
  1310. sizeRootfs += fileInfo.Size()
  1311. }
  1312. return nil
  1313. })
  1314. }
  1315. return sizeRw, sizeRootfs
  1316. }
  1317. func (container *Container) Copy(resource string) (archive.Archive, error) {
  1318. if err := container.EnsureMounted(); err != nil {
  1319. return nil, err
  1320. }
  1321. var filter []string
  1322. basePath := path.Join(container.RootfsPath(), resource)
  1323. stat, err := os.Stat(basePath)
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. if !stat.IsDir() {
  1328. d, f := path.Split(basePath)
  1329. basePath = d
  1330. filter = []string{f}
  1331. } else {
  1332. filter = []string{path.Base(basePath)}
  1333. basePath = path.Dir(basePath)
  1334. }
  1335. return archive.TarFilter(basePath, archive.Uncompressed, filter)
  1336. }
  1337. // Returns true if the container exposes a certain port
  1338. func (container *Container) Exposes(p Port) bool {
  1339. _, exists := container.Config.ExposedPorts[p]
  1340. return exists
  1341. }