container.go 35 KB

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