container.go 32 KB

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