container.go 34 KB

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