container.go 35 KB

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