container.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. package docker
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "github.com/dotcloud/docker/term"
  8. "github.com/dotcloud/docker/utils"
  9. "github.com/kr/pty"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "syscall"
  21. "time"
  22. )
  23. type Container struct {
  24. root string
  25. ID string
  26. Created time.Time
  27. Path string
  28. Args []string
  29. Config *Config
  30. State State
  31. Image string
  32. network *NetworkInterface
  33. NetworkSettings *NetworkSettings
  34. SysInitPath string
  35. ResolvConfPath string
  36. cmd *exec.Cmd
  37. stdout *utils.WriteBroadcaster
  38. stderr *utils.WriteBroadcaster
  39. stdin io.ReadCloser
  40. stdinPipe io.WriteCloser
  41. ptyMaster io.Closer
  42. runtime *Runtime
  43. waitLock chan struct{}
  44. Volumes map[string]string
  45. // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk.
  46. // Easier than migrating older container configs :)
  47. VolumesRW map[string]bool
  48. }
  49. type Config struct {
  50. Hostname string
  51. User string
  52. Memory int64 // Memory limit (in bytes)
  53. MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
  54. CpuShares int64 // CPU shares (relative weight vs. other containers)
  55. AttachStdin bool
  56. AttachStdout bool
  57. AttachStderr bool
  58. PortSpecs []string
  59. Tty bool // Attach standard streams to a tty, including stdin if it is not closed.
  60. OpenStdin bool // Open stdin
  61. StdinOnce bool // If true, close stdin after the 1 attached client disconnects.
  62. Env []string
  63. Cmd []string
  64. Dns []string
  65. Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
  66. Volumes map[string]struct{}
  67. VolumesFrom string
  68. WorkingDir string
  69. Entrypoint []string
  70. NetworkDisabled bool
  71. Privileged bool
  72. }
  73. type HostConfig struct {
  74. Binds []string
  75. ContainerIDFile string
  76. LxcConf []KeyValuePair
  77. }
  78. type BindMap struct {
  79. SrcPath string
  80. DstPath string
  81. Mode string
  82. }
  83. var (
  84. ErrInvaidWorikingDirectory = errors.New("The working directory is invalid. It needs to be an absolute path.")
  85. )
  86. type KeyValuePair struct {
  87. Key string
  88. Value string
  89. }
  90. func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  91. cmd := Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container")
  92. if len(args) > 0 && args[0] != "--help" {
  93. cmd.SetOutput(ioutil.Discard)
  94. cmd.Usage = nil
  95. }
  96. flHostname := cmd.String("h", "", "Container host name")
  97. flWorkingDir := cmd.String("w", "", "Working directory inside the container")
  98. flUser := cmd.String("u", "", "Username or UID")
  99. flDetach := cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id")
  100. flAttach := NewAttachOpts()
  101. cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.")
  102. flStdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  103. flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  104. flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  105. flContainerIDFile := cmd.String("cidfile", "", "Write the container ID to the file")
  106. flNetwork := cmd.Bool("n", true, "Enable networking for this container")
  107. flPrivileged := cmd.Bool("privileged", false, "Give extended privileges to this container")
  108. if capabilities != nil && *flMemory > 0 && !capabilities.MemoryLimit {
  109. //fmt.Fprintf(stdout, "WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  110. *flMemory = 0
  111. }
  112. flCpuShares := cmd.Int64("c", 0, "CPU shares (relative weight)")
  113. var flPorts ListOpts
  114. cmd.Var(&flPorts, "p", "Expose a container's port to the host (use 'docker port' to see the actual mapping)")
  115. var flEnv ListOpts
  116. cmd.Var(&flEnv, "e", "Set environment variables")
  117. var flDns ListOpts
  118. cmd.Var(&flDns, "dns", "Set custom dns servers")
  119. flVolumes := NewPathOpts()
  120. cmd.Var(flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
  121. flVolumesFrom := cmd.String("volumes-from", "", "Mount volumes from the specified container")
  122. flEntrypoint := cmd.String("entrypoint", "", "Overwrite the default entrypoint of the image")
  123. var flLxcOpts ListOpts
  124. cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
  125. if err := cmd.Parse(args); err != nil {
  126. return nil, nil, cmd, err
  127. }
  128. if *flDetach && len(flAttach) > 0 {
  129. return nil, nil, cmd, fmt.Errorf("Conflicting options: -a and -d")
  130. }
  131. if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
  132. return nil, nil, cmd, ErrInvaidWorikingDirectory
  133. }
  134. // If neither -d or -a are set, attach to everything by default
  135. if len(flAttach) == 0 && !*flDetach {
  136. if !*flDetach {
  137. flAttach.Set("stdout")
  138. flAttach.Set("stderr")
  139. if *flStdin {
  140. flAttach.Set("stdin")
  141. }
  142. }
  143. }
  144. var binds []string
  145. // add any bind targets to the list of container volumes
  146. for bind := range flVolumes {
  147. arr := strings.Split(bind, ":")
  148. if len(arr) > 1 {
  149. dstDir := arr[1]
  150. flVolumes[dstDir] = struct{}{}
  151. binds = append(binds, bind)
  152. delete(flVolumes, bind)
  153. }
  154. }
  155. parsedArgs := cmd.Args()
  156. runCmd := []string{}
  157. entrypoint := []string{}
  158. image := ""
  159. if len(parsedArgs) >= 1 {
  160. image = cmd.Arg(0)
  161. }
  162. if len(parsedArgs) > 1 {
  163. runCmd = parsedArgs[1:]
  164. }
  165. if *flEntrypoint != "" {
  166. entrypoint = []string{*flEntrypoint}
  167. }
  168. var lxcConf []KeyValuePair
  169. lxcConf, err := parseLxcConfOpts(flLxcOpts)
  170. if err != nil {
  171. return nil, nil, cmd, err
  172. }
  173. config := &Config{
  174. Hostname: *flHostname,
  175. PortSpecs: flPorts,
  176. User: *flUser,
  177. Tty: *flTty,
  178. NetworkDisabled: !*flNetwork,
  179. OpenStdin: *flStdin,
  180. Memory: *flMemory,
  181. CpuShares: *flCpuShares,
  182. AttachStdin: flAttach.Get("stdin"),
  183. AttachStdout: flAttach.Get("stdout"),
  184. AttachStderr: flAttach.Get("stderr"),
  185. Env: flEnv,
  186. Cmd: runCmd,
  187. Dns: flDns,
  188. Image: image,
  189. Volumes: flVolumes,
  190. VolumesFrom: *flVolumesFrom,
  191. Entrypoint: entrypoint,
  192. Privileged: *flPrivileged,
  193. WorkingDir: *flWorkingDir,
  194. }
  195. hostConfig := &HostConfig{
  196. Binds: binds,
  197. ContainerIDFile: *flContainerIDFile,
  198. LxcConf: lxcConf,
  199. }
  200. if capabilities != nil && *flMemory > 0 && !capabilities.SwapLimit {
  201. //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  202. config.MemorySwap = -1
  203. }
  204. // When allocating stdin in attached mode, close stdin at client disconnect
  205. if config.OpenStdin && config.AttachStdin {
  206. config.StdinOnce = true
  207. }
  208. return config, hostConfig, cmd, nil
  209. }
  210. type PortMapping map[string]string
  211. type NetworkSettings struct {
  212. IPAddress string
  213. IPPrefixLen int
  214. Gateway string
  215. Bridge string
  216. PortMapping map[string]PortMapping
  217. }
  218. // String returns a human-readable description of the port mapping defined in the settings
  219. func (settings *NetworkSettings) PortMappingHuman() string {
  220. var mapping []string
  221. for private, public := range settings.PortMapping["Tcp"] {
  222. mapping = append(mapping, fmt.Sprintf("%s->%s", public, private))
  223. }
  224. for private, public := range settings.PortMapping["Udp"] {
  225. mapping = append(mapping, fmt.Sprintf("%s->%s/udp", public, private))
  226. }
  227. sort.Strings(mapping)
  228. return strings.Join(mapping, ", ")
  229. }
  230. // Inject the io.Reader at the given path. Note: do not close the reader
  231. func (container *Container) Inject(file io.Reader, pth string) error {
  232. // Make sure the directory exists
  233. if err := os.MkdirAll(path.Join(container.rwPath(), path.Dir(pth)), 0755); err != nil {
  234. return err
  235. }
  236. // FIXME: Handle permissions/already existing dest
  237. dest, err := os.Create(path.Join(container.rwPath(), pth))
  238. if err != nil {
  239. return err
  240. }
  241. if _, err := io.Copy(dest, file); err != nil {
  242. return err
  243. }
  244. return nil
  245. }
  246. func (container *Container) Cmd() *exec.Cmd {
  247. return container.cmd
  248. }
  249. func (container *Container) When() time.Time {
  250. return container.Created
  251. }
  252. func (container *Container) FromDisk() error {
  253. data, err := ioutil.ReadFile(container.jsonPath())
  254. if err != nil {
  255. return err
  256. }
  257. // Load container settings
  258. // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it
  259. if err := json.Unmarshal(data, container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
  260. return err
  261. }
  262. return nil
  263. }
  264. func (container *Container) ToDisk() (err error) {
  265. data, err := json.Marshal(container)
  266. if err != nil {
  267. return
  268. }
  269. return ioutil.WriteFile(container.jsonPath(), data, 0666)
  270. }
  271. func (container *Container) ReadHostConfig() (*HostConfig, error) {
  272. data, err := ioutil.ReadFile(container.hostConfigPath())
  273. if err != nil {
  274. return &HostConfig{}, err
  275. }
  276. hostConfig := &HostConfig{}
  277. if err := json.Unmarshal(data, hostConfig); err != nil {
  278. return &HostConfig{}, err
  279. }
  280. return hostConfig, nil
  281. }
  282. func (container *Container) SaveHostConfig(hostConfig *HostConfig) (err error) {
  283. data, err := json.Marshal(hostConfig)
  284. if err != nil {
  285. return
  286. }
  287. return ioutil.WriteFile(container.hostConfigPath(), data, 0666)
  288. }
  289. func (container *Container) generateLXCConfig(hostConfig *HostConfig) error {
  290. fo, err := os.Create(container.lxcConfigPath())
  291. if err != nil {
  292. return err
  293. }
  294. defer fo.Close()
  295. if err := LxcTemplateCompiled.Execute(fo, container); err != nil {
  296. return err
  297. }
  298. if hostConfig != nil {
  299. if err := LxcHostConfigTemplateCompiled.Execute(fo, hostConfig); err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. func (container *Container) startPty() error {
  306. ptyMaster, ptySlave, err := pty.Open()
  307. if err != nil {
  308. return err
  309. }
  310. container.ptyMaster = ptyMaster
  311. container.cmd.Stdout = ptySlave
  312. container.cmd.Stderr = ptySlave
  313. // Copy the PTYs to our broadcasters
  314. go func() {
  315. defer container.stdout.CloseWriters()
  316. utils.Debugf("[startPty] Begin of stdout pipe")
  317. io.Copy(container.stdout, ptyMaster)
  318. utils.Debugf("[startPty] End of stdout pipe")
  319. }()
  320. // stdin
  321. if container.Config.OpenStdin {
  322. container.cmd.Stdin = ptySlave
  323. container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
  324. go func() {
  325. defer container.stdin.Close()
  326. utils.Debugf("[startPty] Begin of stdin pipe")
  327. io.Copy(ptyMaster, container.stdin)
  328. utils.Debugf("[startPty] End of stdin pipe")
  329. }()
  330. }
  331. if err := container.cmd.Start(); err != nil {
  332. return err
  333. }
  334. ptySlave.Close()
  335. return nil
  336. }
  337. func (container *Container) start() error {
  338. container.cmd.Stdout = container.stdout
  339. container.cmd.Stderr = container.stderr
  340. if container.Config.OpenStdin {
  341. stdin, err := container.cmd.StdinPipe()
  342. if err != nil {
  343. return err
  344. }
  345. go func() {
  346. defer stdin.Close()
  347. utils.Debugf("Begin of stdin pipe [start]")
  348. io.Copy(stdin, container.stdin)
  349. utils.Debugf("End of stdin pipe [start]")
  350. }()
  351. }
  352. return container.cmd.Start()
  353. }
  354. func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error {
  355. var cStdout, cStderr io.ReadCloser
  356. var nJobs int
  357. errors := make(chan error, 3)
  358. if stdin != nil && container.Config.OpenStdin {
  359. nJobs += 1
  360. if cStdin, err := container.StdinPipe(); err != nil {
  361. errors <- err
  362. } else {
  363. go func() {
  364. utils.Debugf("[start] attach stdin\n")
  365. defer utils.Debugf("[end] attach stdin\n")
  366. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  367. if container.Config.StdinOnce && !container.Config.Tty {
  368. defer cStdin.Close()
  369. } else {
  370. if cStdout != nil {
  371. defer cStdout.Close()
  372. }
  373. if cStderr != nil {
  374. defer cStderr.Close()
  375. }
  376. }
  377. if container.Config.Tty {
  378. _, err = utils.CopyEscapable(cStdin, stdin)
  379. } else {
  380. _, err = io.Copy(cStdin, stdin)
  381. }
  382. if err != nil {
  383. utils.Debugf("[error] attach stdin: %s\n", err)
  384. }
  385. // Discard error, expecting pipe error
  386. errors <- nil
  387. }()
  388. }
  389. }
  390. if stdout != nil {
  391. nJobs += 1
  392. if p, err := container.StdoutPipe(); err != nil {
  393. errors <- err
  394. } else {
  395. cStdout = p
  396. go func() {
  397. utils.Debugf("[start] attach stdout\n")
  398. defer utils.Debugf("[end] attach stdout\n")
  399. // If we are in StdinOnce mode, then close stdin
  400. if container.Config.StdinOnce {
  401. if stdin != nil {
  402. defer stdin.Close()
  403. }
  404. if stdinCloser != nil {
  405. defer stdinCloser.Close()
  406. }
  407. }
  408. _, err := io.Copy(stdout, cStdout)
  409. if err != nil {
  410. utils.Debugf("[error] attach stdout: %s\n", err)
  411. }
  412. errors <- err
  413. }()
  414. }
  415. } else {
  416. go func() {
  417. if stdinCloser != nil {
  418. defer stdinCloser.Close()
  419. }
  420. if cStdout, err := container.StdoutPipe(); err != nil {
  421. utils.Debugf("Error stdout pipe")
  422. } else {
  423. io.Copy(&utils.NopWriter{}, cStdout)
  424. }
  425. }()
  426. }
  427. if stderr != nil {
  428. nJobs += 1
  429. if p, err := container.StderrPipe(); err != nil {
  430. errors <- err
  431. } else {
  432. cStderr = p
  433. go func() {
  434. utils.Debugf("[start] attach stderr\n")
  435. defer utils.Debugf("[end] attach stderr\n")
  436. // If we are in StdinOnce mode, then close stdin
  437. if container.Config.StdinOnce {
  438. if stdin != nil {
  439. defer stdin.Close()
  440. }
  441. if stdinCloser != nil {
  442. defer stdinCloser.Close()
  443. }
  444. }
  445. _, err := io.Copy(stderr, cStderr)
  446. if err != nil {
  447. utils.Debugf("[error] attach stderr: %s\n", err)
  448. }
  449. errors <- err
  450. }()
  451. }
  452. } else {
  453. go func() {
  454. if stdinCloser != nil {
  455. defer stdinCloser.Close()
  456. }
  457. if cStderr, err := container.StderrPipe(); err != nil {
  458. utils.Debugf("Error stdout pipe")
  459. } else {
  460. io.Copy(&utils.NopWriter{}, cStderr)
  461. }
  462. }()
  463. }
  464. return utils.Go(func() error {
  465. if cStdout != nil {
  466. defer cStdout.Close()
  467. }
  468. if cStderr != nil {
  469. defer cStderr.Close()
  470. }
  471. // FIXME: how do clean up the stdin goroutine without the unwanted side effect
  472. // of closing the passed stdin? Add an intermediary io.Pipe?
  473. for i := 0; i < nJobs; i += 1 {
  474. utils.Debugf("Waiting for job %d/%d\n", i+1, nJobs)
  475. if err := <-errors; err != nil {
  476. utils.Debugf("Job %d returned error %s. Aborting all jobs\n", i+1, err)
  477. return err
  478. }
  479. utils.Debugf("Job %d completed successfully\n", i+1)
  480. }
  481. utils.Debugf("All jobs completed successfully\n")
  482. return nil
  483. })
  484. }
  485. func (container *Container) Start(hostConfig *HostConfig) error {
  486. container.State.Lock()
  487. defer container.State.Unlock()
  488. if len(hostConfig.Binds) == 0 && len(hostConfig.LxcConf) == 0 {
  489. hostConfig, _ = container.ReadHostConfig()
  490. }
  491. if container.State.Running {
  492. return fmt.Errorf("The container %s is already running.", container.ID)
  493. }
  494. if err := container.EnsureMounted(); err != nil {
  495. return err
  496. }
  497. if container.runtime.networkManager.disabled {
  498. container.Config.NetworkDisabled = true
  499. } else {
  500. if err := container.allocateNetwork(); err != nil {
  501. return err
  502. }
  503. }
  504. // Make sure the config is compatible with the current kernel
  505. if container.Config.Memory > 0 && !container.runtime.capabilities.MemoryLimit {
  506. log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
  507. container.Config.Memory = 0
  508. }
  509. if container.Config.Memory > 0 && !container.runtime.capabilities.SwapLimit {
  510. log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  511. container.Config.MemorySwap = -1
  512. }
  513. if container.runtime.capabilities.IPv4ForwardingDisabled {
  514. log.Printf("WARNING: IPv4 forwarding is disabled. Networking will not work")
  515. }
  516. // Create the requested bind mounts
  517. binds := make(map[string]BindMap)
  518. // Define illegal container destinations
  519. illegalDsts := []string{"/", "."}
  520. for _, bind := range hostConfig.Binds {
  521. // FIXME: factorize bind parsing in parseBind
  522. var src, dst, mode string
  523. arr := strings.Split(bind, ":")
  524. if len(arr) == 2 {
  525. src = arr[0]
  526. dst = arr[1]
  527. mode = "rw"
  528. } else if len(arr) == 3 {
  529. src = arr[0]
  530. dst = arr[1]
  531. mode = arr[2]
  532. } else {
  533. return fmt.Errorf("Invalid bind specification: %s", bind)
  534. }
  535. // Bail if trying to mount to an illegal destination
  536. for _, illegal := range illegalDsts {
  537. if dst == illegal {
  538. return fmt.Errorf("Illegal bind destination: %s", dst)
  539. }
  540. }
  541. bindMap := BindMap{
  542. SrcPath: src,
  543. DstPath: dst,
  544. Mode: mode,
  545. }
  546. binds[path.Clean(dst)] = bindMap
  547. }
  548. if container.Volumes == nil || len(container.Volumes) == 0 {
  549. container.Volumes = make(map[string]string)
  550. container.VolumesRW = make(map[string]bool)
  551. }
  552. // Apply volumes from another container if requested
  553. if container.Config.VolumesFrom != "" {
  554. c := container.runtime.Get(container.Config.VolumesFrom)
  555. if c == nil {
  556. return fmt.Errorf("Container %s not found. Impossible to mount its volumes", container.ID)
  557. }
  558. for volPath, id := range c.Volumes {
  559. if _, exists := container.Volumes[volPath]; exists {
  560. continue
  561. }
  562. if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil {
  563. return nil
  564. }
  565. container.Volumes[volPath] = id
  566. if isRW, exists := c.VolumesRW[volPath]; exists {
  567. container.VolumesRW[volPath] = isRW
  568. }
  569. }
  570. }
  571. // Create the requested volumes if they don't exist
  572. for volPath := range container.Config.Volumes {
  573. volPath = path.Clean(volPath)
  574. // Skip existing volumes
  575. if _, exists := container.Volumes[volPath]; exists {
  576. continue
  577. }
  578. // If an external bind is defined for this volume, use that as a source
  579. if bindMap, exists := binds[volPath]; exists {
  580. container.Volumes[volPath] = bindMap.SrcPath
  581. if strings.ToLower(bindMap.Mode) == "rw" {
  582. container.VolumesRW[volPath] = true
  583. }
  584. // Otherwise create an directory in $ROOT/volumes/ and use that
  585. } else {
  586. c, err := container.runtime.volumes.Create(nil, container, "", "", nil)
  587. if err != nil {
  588. return err
  589. }
  590. srcPath, err := c.layer()
  591. if err != nil {
  592. return err
  593. }
  594. container.Volumes[volPath] = srcPath
  595. container.VolumesRW[volPath] = true // RW by default
  596. }
  597. // Create the mountpoint
  598. if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil {
  599. return nil
  600. }
  601. }
  602. if err := container.generateLXCConfig(hostConfig); err != nil {
  603. return err
  604. }
  605. params := []string{
  606. "-n", container.ID,
  607. "-f", container.lxcConfigPath(),
  608. "--",
  609. "/.dockerinit",
  610. }
  611. // Networking
  612. if !container.Config.NetworkDisabled {
  613. params = append(params, "-g", container.network.Gateway.String())
  614. }
  615. // User
  616. if container.Config.User != "" {
  617. params = append(params, "-u", container.Config.User)
  618. }
  619. if container.Config.Tty {
  620. params = append(params, "-e", "TERM=xterm")
  621. }
  622. // Setup environment
  623. params = append(params,
  624. "-e", "HOME=/",
  625. "-e", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  626. "-e", "container=lxc",
  627. "-e", "HOSTNAME="+container.Config.Hostname,
  628. )
  629. if container.Config.WorkingDir != "" {
  630. workingDir := path.Clean(container.Config.WorkingDir)
  631. utils.Debugf("[working dir] working dir is %s", workingDir)
  632. if err := os.MkdirAll(path.Join(container.RootfsPath(), workingDir), 0755); err != nil {
  633. return nil
  634. }
  635. params = append(params,
  636. "-w", workingDir,
  637. )
  638. }
  639. for _, elem := range container.Config.Env {
  640. params = append(params, "-e", elem)
  641. }
  642. // Program
  643. params = append(params, "--", container.Path)
  644. params = append(params, container.Args...)
  645. container.cmd = exec.Command("lxc-start", params...)
  646. // Setup logging of stdout and stderr to disk
  647. if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil {
  648. return err
  649. }
  650. if err := container.runtime.LogToDisk(container.stderr, container.logPath("json"), "stderr"); err != nil {
  651. return err
  652. }
  653. var err error
  654. if container.Config.Tty {
  655. err = container.startPty()
  656. } else {
  657. err = container.start()
  658. }
  659. if err != nil {
  660. return err
  661. }
  662. // FIXME: save state on disk *first*, then converge
  663. // this way disk state is used as a journal, eg. we can restore after crash etc.
  664. container.State.setRunning(container.cmd.Process.Pid)
  665. // Init the lock
  666. container.waitLock = make(chan struct{})
  667. container.ToDisk()
  668. container.SaveHostConfig(hostConfig)
  669. go container.monitor()
  670. return nil
  671. }
  672. func (container *Container) Run() error {
  673. hostConfig := &HostConfig{}
  674. if err := container.Start(hostConfig); err != nil {
  675. return err
  676. }
  677. container.Wait()
  678. return nil
  679. }
  680. func (container *Container) Output() (output []byte, err error) {
  681. pipe, err := container.StdoutPipe()
  682. if err != nil {
  683. return nil, err
  684. }
  685. defer pipe.Close()
  686. hostConfig := &HostConfig{}
  687. if err := container.Start(hostConfig); err != nil {
  688. return nil, err
  689. }
  690. output, err = ioutil.ReadAll(pipe)
  691. container.Wait()
  692. return output, err
  693. }
  694. // StdinPipe() returns a pipe connected to the standard input of the container's
  695. // active process.
  696. //
  697. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  698. return container.stdinPipe, nil
  699. }
  700. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  701. reader, writer := io.Pipe()
  702. container.stdout.AddWriter(writer, "")
  703. return utils.NewBufReader(reader), nil
  704. }
  705. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  706. reader, writer := io.Pipe()
  707. container.stderr.AddWriter(writer, "")
  708. return utils.NewBufReader(reader), nil
  709. }
  710. func (container *Container) allocateNetwork() error {
  711. if container.Config.NetworkDisabled {
  712. return nil
  713. }
  714. iface, err := container.runtime.networkManager.Allocate()
  715. if err != nil {
  716. return err
  717. }
  718. container.NetworkSettings.PortMapping = make(map[string]PortMapping)
  719. container.NetworkSettings.PortMapping["Tcp"] = make(PortMapping)
  720. container.NetworkSettings.PortMapping["Udp"] = make(PortMapping)
  721. for _, spec := range container.Config.PortSpecs {
  722. nat, err := iface.AllocatePort(spec)
  723. if err != nil {
  724. iface.Release()
  725. return err
  726. }
  727. proto := strings.Title(nat.Proto)
  728. backend, frontend := strconv.Itoa(nat.Backend), strconv.Itoa(nat.Frontend)
  729. container.NetworkSettings.PortMapping[proto][backend] = frontend
  730. }
  731. container.network = iface
  732. container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface
  733. container.NetworkSettings.IPAddress = iface.IPNet.IP.String()
  734. container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size()
  735. container.NetworkSettings.Gateway = iface.Gateway.String()
  736. return nil
  737. }
  738. func (container *Container) releaseNetwork() {
  739. if container.Config.NetworkDisabled {
  740. return
  741. }
  742. container.network.Release()
  743. container.network = nil
  744. container.NetworkSettings = &NetworkSettings{}
  745. }
  746. // FIXME: replace this with a control socket within docker-init
  747. func (container *Container) waitLxc() error {
  748. for {
  749. output, err := exec.Command("lxc-info", "-n", container.ID).CombinedOutput()
  750. if err != nil {
  751. return err
  752. }
  753. if !strings.Contains(string(output), "RUNNING") {
  754. return nil
  755. }
  756. time.Sleep(500 * time.Millisecond)
  757. }
  758. }
  759. func (container *Container) monitor() {
  760. // Wait for the program to exit
  761. utils.Debugf("Waiting for process")
  762. // If the command does not exists, try to wait via lxc
  763. if container.cmd == nil {
  764. if err := container.waitLxc(); err != nil {
  765. utils.Debugf("%s: Process: %s", container.ID, err)
  766. }
  767. } else {
  768. if err := container.cmd.Wait(); err != nil {
  769. // Discard the error as any signals or non 0 returns will generate an error
  770. utils.Debugf("%s: Process: %s", container.ID, err)
  771. }
  772. }
  773. utils.Debugf("Process finished")
  774. if container.runtime != nil && container.runtime.srv != nil {
  775. container.runtime.srv.LogEvent("die", container.ShortID(), container.runtime.repositories.ImageName(container.Image))
  776. }
  777. exitCode := -1
  778. if container.cmd != nil {
  779. exitCode = container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
  780. }
  781. // Cleanup
  782. container.releaseNetwork()
  783. if container.Config.OpenStdin {
  784. if err := container.stdin.Close(); err != nil {
  785. utils.Debugf("%s: Error close stdin: %s", container.ID, err)
  786. }
  787. }
  788. if err := container.stdout.CloseWriters(); err != nil {
  789. utils.Debugf("%s: Error close stdout: %s", container.ID, err)
  790. }
  791. if err := container.stderr.CloseWriters(); err != nil {
  792. utils.Debugf("%s: Error close stderr: %s", container.ID, err)
  793. }
  794. if container.ptyMaster != nil {
  795. if err := container.ptyMaster.Close(); err != nil {
  796. utils.Debugf("%s: Error closing Pty master: %s", container.ID, err)
  797. }
  798. }
  799. if err := container.Unmount(); err != nil {
  800. log.Printf("%v: Failed to umount filesystem: %v", container.ID, err)
  801. }
  802. // Re-create a brand new stdin pipe once the container exited
  803. if container.Config.OpenStdin {
  804. container.stdin, container.stdinPipe = io.Pipe()
  805. }
  806. // Report status back
  807. container.State.setStopped(exitCode)
  808. // Release the lock
  809. close(container.waitLock)
  810. if err := container.ToDisk(); err != nil {
  811. // FIXME: there is a race condition here which causes this to fail during the unit tests.
  812. // If another goroutine was waiting for Wait() to return before removing the container's root
  813. // from the filesystem... At this point it may already have done so.
  814. // This is because State.setStopped() has already been called, and has caused Wait()
  815. // to return.
  816. // FIXME: why are we serializing running state to disk in the first place?
  817. //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
  818. }
  819. }
  820. func (container *Container) kill() error {
  821. if !container.State.Running {
  822. return nil
  823. }
  824. // Sending SIGKILL to the process via lxc
  825. output, err := exec.Command("lxc-kill", "-n", container.ID, "9").CombinedOutput()
  826. if err != nil {
  827. log.Printf("error killing container %s (%s, %s)", container.ID, output, err)
  828. }
  829. // 2. Wait for the process to die, in last resort, try to kill the process directly
  830. if err := container.WaitTimeout(10 * time.Second); err != nil {
  831. if container.cmd == nil {
  832. return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", container.ID)
  833. }
  834. log.Printf("Container %s failed to exit within 10 seconds of lxc SIGKILL - trying direct SIGKILL", container.ID)
  835. if err := container.cmd.Process.Kill(); err != nil {
  836. return err
  837. }
  838. }
  839. // Wait for the container to be actually stopped
  840. container.Wait()
  841. return nil
  842. }
  843. func (container *Container) Kill() error {
  844. container.State.Lock()
  845. defer container.State.Unlock()
  846. if !container.State.Running {
  847. return nil
  848. }
  849. return container.kill()
  850. }
  851. func (container *Container) Stop(seconds int) error {
  852. container.State.Lock()
  853. defer container.State.Unlock()
  854. if !container.State.Running {
  855. return nil
  856. }
  857. // 1. Send a SIGTERM
  858. if output, err := exec.Command("lxc-kill", "-n", container.ID, "15").CombinedOutput(); err != nil {
  859. log.Print(string(output))
  860. log.Print("Failed to send SIGTERM to the process, force killing")
  861. if err := container.kill(); err != nil {
  862. return err
  863. }
  864. }
  865. // 2. Wait for the process to exit on its own
  866. if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
  867. log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  868. if err := container.kill(); err != nil {
  869. return err
  870. }
  871. }
  872. return nil
  873. }
  874. func (container *Container) Restart(seconds int) error {
  875. if err := container.Stop(seconds); err != nil {
  876. return err
  877. }
  878. hostConfig := &HostConfig{}
  879. if err := container.Start(hostConfig); err != nil {
  880. return err
  881. }
  882. return nil
  883. }
  884. // Wait blocks until the container stops running, then returns its exit code.
  885. func (container *Container) Wait() int {
  886. <-container.waitLock
  887. return container.State.ExitCode
  888. }
  889. func (container *Container) Resize(h, w int) error {
  890. pty, ok := container.ptyMaster.(*os.File)
  891. if !ok {
  892. return fmt.Errorf("ptyMaster does not have Fd() method")
  893. }
  894. return term.SetWinsize(pty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  895. }
  896. func (container *Container) ExportRw() (Archive, error) {
  897. return Tar(container.rwPath(), Uncompressed)
  898. }
  899. func (container *Container) RwChecksum() (string, error) {
  900. rwData, err := Tar(container.rwPath(), Xz)
  901. if err != nil {
  902. return "", err
  903. }
  904. return utils.HashData(rwData)
  905. }
  906. func (container *Container) Export() (Archive, error) {
  907. if err := container.EnsureMounted(); err != nil {
  908. return nil, err
  909. }
  910. return Tar(container.RootfsPath(), Uncompressed)
  911. }
  912. func (container *Container) WaitTimeout(timeout time.Duration) error {
  913. done := make(chan bool)
  914. go func() {
  915. container.Wait()
  916. done <- true
  917. }()
  918. select {
  919. case <-time.After(timeout):
  920. return fmt.Errorf("Timed Out")
  921. case <-done:
  922. return nil
  923. }
  924. }
  925. func (container *Container) EnsureMounted() error {
  926. if mounted, err := container.Mounted(); err != nil {
  927. return err
  928. } else if mounted {
  929. return nil
  930. }
  931. return container.Mount()
  932. }
  933. func (container *Container) Mount() error {
  934. image, err := container.GetImage()
  935. if err != nil {
  936. return err
  937. }
  938. return image.Mount(container.RootfsPath(), container.rwPath())
  939. }
  940. func (container *Container) Changes() ([]Change, error) {
  941. image, err := container.GetImage()
  942. if err != nil {
  943. return nil, err
  944. }
  945. return image.Changes(container.rwPath())
  946. }
  947. func (container *Container) GetImage() (*Image, error) {
  948. if container.runtime == nil {
  949. return nil, fmt.Errorf("Can't get image of unregistered container")
  950. }
  951. return container.runtime.graph.Get(container.Image)
  952. }
  953. func (container *Container) Mounted() (bool, error) {
  954. return Mounted(container.RootfsPath())
  955. }
  956. func (container *Container) Unmount() error {
  957. return Unmount(container.RootfsPath())
  958. }
  959. // ShortID returns a shorthand version of the container's id for convenience.
  960. // A collision with other container shorthands is very unlikely, but possible.
  961. // In case of a collision a lookup with Runtime.Get() will fail, and the caller
  962. // will need to use a langer prefix, or the full-length container Id.
  963. func (container *Container) ShortID() string {
  964. return utils.TruncateID(container.ID)
  965. }
  966. func (container *Container) logPath(name string) string {
  967. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name))
  968. }
  969. func (container *Container) ReadLog(name string) (io.Reader, error) {
  970. return os.Open(container.logPath(name))
  971. }
  972. func (container *Container) hostConfigPath() string {
  973. return path.Join(container.root, "hostconfig.json")
  974. }
  975. func (container *Container) jsonPath() string {
  976. return path.Join(container.root, "config.json")
  977. }
  978. func (container *Container) lxcConfigPath() string {
  979. return path.Join(container.root, "config.lxc")
  980. }
  981. // This method must be exported to be used from the lxc template
  982. func (container *Container) RootfsPath() string {
  983. return path.Join(container.root, "rootfs")
  984. }
  985. func (container *Container) rwPath() string {
  986. return path.Join(container.root, "rw")
  987. }
  988. func validateID(id string) error {
  989. if id == "" {
  990. return fmt.Errorf("Invalid empty id")
  991. }
  992. return nil
  993. }
  994. // GetSize, return real size, virtual size
  995. func (container *Container) GetSize() (int64, int64) {
  996. var sizeRw, sizeRootfs int64
  997. filepath.Walk(container.rwPath(), func(path string, fileInfo os.FileInfo, err error) error {
  998. if fileInfo != nil {
  999. sizeRw += fileInfo.Size()
  1000. }
  1001. return nil
  1002. })
  1003. _, err := os.Stat(container.RootfsPath())
  1004. if err == nil {
  1005. filepath.Walk(container.RootfsPath(), func(path string, fileInfo os.FileInfo, err error) error {
  1006. if fileInfo != nil {
  1007. sizeRootfs += fileInfo.Size()
  1008. }
  1009. return nil
  1010. })
  1011. }
  1012. return sizeRw, sizeRootfs
  1013. }
  1014. func (container *Container) Copy(resource string) (Archive, error) {
  1015. if err := container.EnsureMounted(); err != nil {
  1016. return nil, err
  1017. }
  1018. var filter []string
  1019. basePath := path.Join(container.RootfsPath(), resource)
  1020. stat, err := os.Stat(basePath)
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. if !stat.IsDir() {
  1025. d, f := path.Split(basePath)
  1026. basePath = d
  1027. filter = []string{f}
  1028. } else {
  1029. filter = []string{path.Base(basePath)}
  1030. basePath = path.Dir(basePath)
  1031. }
  1032. return TarFilter(basePath, Uncompressed, filter)
  1033. }