container.go 33 KB

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