container.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package docker
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/dotcloud/docker/rcli"
  7. "github.com/kr/pty"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "strconv"
  15. "syscall"
  16. "time"
  17. )
  18. type Container struct {
  19. root string
  20. Id string
  21. Created time.Time
  22. Path string
  23. Args []string
  24. Config *Config
  25. State State
  26. Image string
  27. network *NetworkInterface
  28. NetworkSettings *NetworkSettings
  29. SysInitPath string
  30. cmd *exec.Cmd
  31. stdout *writeBroadcaster
  32. stderr *writeBroadcaster
  33. stdin io.ReadCloser
  34. stdinPipe io.WriteCloser
  35. stdoutLog *os.File
  36. stderrLog *os.File
  37. runtime *Runtime
  38. }
  39. type Config struct {
  40. Hostname string
  41. User string
  42. Memory int64 // Memory limit (in bytes)
  43. MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap
  44. Detach bool
  45. Ports []int
  46. Tty bool // Attach standard streams to a tty, including stdin if it is not closed.
  47. OpenStdin bool // Open stdin
  48. Env []string
  49. Cmd []string
  50. Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
  51. }
  52. func ParseRun(args []string, stdout io.Writer) (*Config, error) {
  53. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  54. if len(args) > 0 && args[0] != "--help" {
  55. cmd.SetOutput(ioutil.Discard)
  56. }
  57. flUser := cmd.String("u", "", "Username or UID")
  58. flDetach := cmd.Bool("d", false, "Detached mode: leave the container running in the background")
  59. flStdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  60. flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  61. flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  62. var flPorts ports
  63. cmd.Var(&flPorts, "p", "Map a network port to the container")
  64. var flEnv ListOpts
  65. cmd.Var(&flEnv, "e", "Set environment variables")
  66. if err := cmd.Parse(args); err != nil {
  67. return nil, err
  68. }
  69. parsedArgs := cmd.Args()
  70. runCmd := []string{}
  71. image := ""
  72. if len(parsedArgs) >= 1 {
  73. image = cmd.Arg(0)
  74. }
  75. if len(parsedArgs) > 1 {
  76. runCmd = parsedArgs[1:]
  77. }
  78. config := &Config{
  79. Ports: flPorts,
  80. User: *flUser,
  81. Tty: *flTty,
  82. OpenStdin: *flStdin,
  83. Memory: *flMemory,
  84. Detach: *flDetach,
  85. Env: flEnv,
  86. Cmd: runCmd,
  87. Image: image,
  88. }
  89. return config, nil
  90. }
  91. type NetworkSettings struct {
  92. IpAddress string
  93. IpPrefixLen int
  94. Gateway string
  95. PortMapping map[string]string
  96. }
  97. func (container *Container) Cmd() *exec.Cmd {
  98. return container.cmd
  99. }
  100. func (container *Container) When() time.Time {
  101. return container.Created
  102. }
  103. func (container *Container) FromDisk() error {
  104. data, err := ioutil.ReadFile(container.jsonPath())
  105. if err != nil {
  106. return err
  107. }
  108. // Load container settings
  109. if err := json.Unmarshal(data, container); err != nil {
  110. return err
  111. }
  112. return nil
  113. }
  114. func (container *Container) ToDisk() (err error) {
  115. data, err := json.Marshal(container)
  116. if err != nil {
  117. return
  118. }
  119. return ioutil.WriteFile(container.jsonPath(), data, 0666)
  120. }
  121. func (container *Container) generateLXCConfig() error {
  122. fo, err := os.Create(container.lxcConfigPath())
  123. if err != nil {
  124. return err
  125. }
  126. defer fo.Close()
  127. if err := LxcTemplateCompiled.Execute(fo, container); err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. func (container *Container) startPty() error {
  133. stdoutMaster, stdoutSlave, err := pty.Open()
  134. if err != nil {
  135. return err
  136. }
  137. container.cmd.Stdout = stdoutSlave
  138. stderrMaster, stderrSlave, err := pty.Open()
  139. if err != nil {
  140. return err
  141. }
  142. container.cmd.Stderr = stderrSlave
  143. // Copy the PTYs to our broadcasters
  144. go func() {
  145. defer container.stdout.Close()
  146. io.Copy(container.stdout, stdoutMaster)
  147. }()
  148. go func() {
  149. defer container.stderr.Close()
  150. io.Copy(container.stderr, stderrMaster)
  151. }()
  152. // stdin
  153. var stdinSlave io.ReadCloser
  154. if container.Config.OpenStdin {
  155. stdinMaster, stdinSlave, err := pty.Open()
  156. if err != nil {
  157. return err
  158. }
  159. container.cmd.Stdin = stdinSlave
  160. // FIXME: The following appears to be broken.
  161. // "cannot set terminal process group (-1): Inappropriate ioctl for device"
  162. // container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
  163. go func() {
  164. defer container.stdin.Close()
  165. io.Copy(stdinMaster, container.stdin)
  166. }()
  167. }
  168. if err := container.cmd.Start(); err != nil {
  169. return err
  170. }
  171. stdoutSlave.Close()
  172. stderrSlave.Close()
  173. if stdinSlave != nil {
  174. stdinSlave.Close()
  175. }
  176. return nil
  177. }
  178. func (container *Container) start() error {
  179. container.cmd.Stdout = container.stdout
  180. container.cmd.Stderr = container.stderr
  181. if container.Config.OpenStdin {
  182. stdin, err := container.cmd.StdinPipe()
  183. if err != nil {
  184. return err
  185. }
  186. go func() {
  187. defer stdin.Close()
  188. io.Copy(stdin, container.stdin)
  189. }()
  190. }
  191. return container.cmd.Start()
  192. }
  193. func (container *Container) Start() error {
  194. if err := container.EnsureMounted(); err != nil {
  195. return err
  196. }
  197. if err := container.allocateNetwork(); err != nil {
  198. return err
  199. }
  200. if err := container.generateLXCConfig(); err != nil {
  201. return err
  202. }
  203. params := []string{
  204. "-n", container.Id,
  205. "-f", container.lxcConfigPath(),
  206. "--",
  207. "/sbin/init",
  208. }
  209. // Networking
  210. params = append(params, "-g", container.network.Gateway.String())
  211. // User
  212. if container.Config.User != "" {
  213. params = append(params, "-u", container.Config.User)
  214. }
  215. // Program
  216. params = append(params, "--", container.Path)
  217. params = append(params, container.Args...)
  218. container.cmd = exec.Command("/usr/bin/lxc-start", params...)
  219. // Setup environment
  220. container.cmd.Env = append(
  221. []string{
  222. "HOME=/",
  223. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  224. },
  225. container.Config.Env...,
  226. )
  227. var err error
  228. if container.Config.Tty {
  229. container.cmd.Env = append(
  230. []string{"TERM=xterm"},
  231. container.cmd.Env...,
  232. )
  233. err = container.startPty()
  234. } else {
  235. err = container.start()
  236. }
  237. if err != nil {
  238. return err
  239. }
  240. // FIXME: save state on disk *first*, then converge
  241. // this way disk state is used as a journal, eg. we can restore after crash etc.
  242. container.State.setRunning(container.cmd.Process.Pid)
  243. container.ToDisk()
  244. go container.monitor()
  245. return nil
  246. }
  247. func (container *Container) Run() error {
  248. if err := container.Start(); err != nil {
  249. return err
  250. }
  251. container.Wait()
  252. return nil
  253. }
  254. func (container *Container) Output() (output []byte, err error) {
  255. pipe, err := container.StdoutPipe()
  256. if err != nil {
  257. return nil, err
  258. }
  259. defer pipe.Close()
  260. if err := container.Start(); err != nil {
  261. return nil, err
  262. }
  263. output, err = ioutil.ReadAll(pipe)
  264. container.Wait()
  265. return output, err
  266. }
  267. // StdinPipe() returns a pipe connected to the standard input of the container's
  268. // active process.
  269. //
  270. func (container *Container) StdinPipe() (io.WriteCloser, error) {
  271. return container.stdinPipe, nil
  272. }
  273. func (container *Container) StdoutPipe() (io.ReadCloser, error) {
  274. reader, writer := io.Pipe()
  275. container.stdout.AddWriter(writer)
  276. return newBufReader(reader), nil
  277. }
  278. func (container *Container) StderrPipe() (io.ReadCloser, error) {
  279. reader, writer := io.Pipe()
  280. container.stderr.AddWriter(writer)
  281. return newBufReader(reader), nil
  282. }
  283. func (container *Container) allocateNetwork() error {
  284. iface, err := container.runtime.networkManager.Allocate()
  285. if err != nil {
  286. return err
  287. }
  288. container.NetworkSettings.PortMapping = make(map[string]string)
  289. for _, port := range container.Config.Ports {
  290. if extPort, err := iface.AllocatePort(port); err != nil {
  291. iface.Release()
  292. return err
  293. } else {
  294. container.NetworkSettings.PortMapping[strconv.Itoa(port)] = strconv.Itoa(extPort)
  295. }
  296. }
  297. container.network = iface
  298. container.NetworkSettings.IpAddress = iface.IPNet.IP.String()
  299. container.NetworkSettings.IpPrefixLen, _ = iface.IPNet.Mask.Size()
  300. container.NetworkSettings.Gateway = iface.Gateway.String()
  301. return nil
  302. }
  303. func (container *Container) releaseNetwork() error {
  304. err := container.network.Release()
  305. container.network = nil
  306. container.NetworkSettings = &NetworkSettings{}
  307. return err
  308. }
  309. func (container *Container) monitor() {
  310. // Wait for the program to exit
  311. container.cmd.Wait()
  312. exitCode := container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
  313. // Cleanup
  314. if err := container.releaseNetwork(); err != nil {
  315. log.Printf("%v: Failed to release network: %v", container.Id, err)
  316. }
  317. container.stdout.Close()
  318. container.stderr.Close()
  319. if err := container.Unmount(); err != nil {
  320. log.Printf("%v: Failed to umount filesystem: %v", container.Id, err)
  321. }
  322. // Re-create a brand new stdin pipe once the container exited
  323. if container.Config.OpenStdin {
  324. container.stdin, container.stdinPipe = io.Pipe()
  325. }
  326. // Report status back
  327. container.State.setStopped(exitCode)
  328. container.ToDisk()
  329. }
  330. func (container *Container) kill() error {
  331. if container.cmd == nil {
  332. return nil
  333. }
  334. if err := container.cmd.Process.Kill(); err != nil {
  335. return err
  336. }
  337. // Wait for the container to be actually stopped
  338. container.Wait()
  339. return nil
  340. }
  341. func (container *Container) Kill() error {
  342. if !container.State.Running {
  343. return nil
  344. }
  345. return container.kill()
  346. }
  347. func (container *Container) Stop() error {
  348. if !container.State.Running {
  349. return nil
  350. }
  351. // 1. Send a SIGTERM
  352. if output, err := exec.Command("/usr/bin/lxc-kill", "-n", container.Id, "15").CombinedOutput(); err != nil {
  353. log.Printf(string(output))
  354. log.Printf("Failed to send SIGTERM to the process, force killing")
  355. if err := container.Kill(); err != nil {
  356. return err
  357. }
  358. }
  359. // 2. Wait for the process to exit on its own
  360. if err := container.WaitTimeout(10 * time.Second); err != nil {
  361. log.Printf("Container %v failed to exit within 10 seconds of SIGTERM - using the force", container.Id)
  362. if err := container.Kill(); err != nil {
  363. return err
  364. }
  365. }
  366. return nil
  367. }
  368. func (container *Container) Restart() error {
  369. if err := container.Stop(); err != nil {
  370. return err
  371. }
  372. if err := container.Start(); err != nil {
  373. return err
  374. }
  375. return nil
  376. }
  377. // Wait blocks until the container stops running, then returns its exit code.
  378. func (container *Container) Wait() int {
  379. for container.State.Running {
  380. container.State.wait()
  381. }
  382. return container.State.ExitCode
  383. }
  384. func (container *Container) ExportRw() (Archive, error) {
  385. return Tar(container.rwPath(), Uncompressed)
  386. }
  387. func (container *Container) Export() (Archive, error) {
  388. if err := container.EnsureMounted(); err != nil {
  389. return nil, err
  390. }
  391. return Tar(container.RootfsPath(), Uncompressed)
  392. }
  393. func (container *Container) WaitTimeout(timeout time.Duration) error {
  394. done := make(chan bool)
  395. go func() {
  396. container.Wait()
  397. done <- true
  398. }()
  399. select {
  400. case <-time.After(timeout):
  401. return errors.New("Timed Out")
  402. case <-done:
  403. return nil
  404. }
  405. return nil
  406. }
  407. func (container *Container) EnsureMounted() error {
  408. if mounted, err := container.Mounted(); err != nil {
  409. return err
  410. } else if mounted {
  411. return nil
  412. }
  413. return container.Mount()
  414. }
  415. func (container *Container) Mount() error {
  416. image, err := container.GetImage()
  417. if err != nil {
  418. return err
  419. }
  420. return image.Mount(container.RootfsPath(), container.rwPath())
  421. }
  422. func (container *Container) Changes() ([]Change, error) {
  423. image, err := container.GetImage()
  424. if err != nil {
  425. return nil, err
  426. }
  427. return image.Changes(container.rwPath())
  428. }
  429. func (container *Container) GetImage() (*Image, error) {
  430. if container.runtime == nil {
  431. return nil, fmt.Errorf("Can't get image of unregistered container")
  432. }
  433. return container.runtime.graph.Get(container.Image)
  434. }
  435. func (container *Container) Mounted() (bool, error) {
  436. return Mounted(container.RootfsPath())
  437. }
  438. func (container *Container) Unmount() error {
  439. return Unmount(container.RootfsPath())
  440. }
  441. func (container *Container) logPath(name string) string {
  442. return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.Id, name))
  443. }
  444. func (container *Container) ReadLog(name string) (io.Reader, error) {
  445. return os.Open(container.logPath(name))
  446. }
  447. func (container *Container) jsonPath() string {
  448. return path.Join(container.root, "config.json")
  449. }
  450. func (container *Container) lxcConfigPath() string {
  451. return path.Join(container.root, "config.lxc")
  452. }
  453. // This method must be exported to be used from the lxc template
  454. func (container *Container) RootfsPath() string {
  455. return path.Join(container.root, "rootfs")
  456. }
  457. func (container *Container) rwPath() string {
  458. return path.Join(container.root, "rw")
  459. }
  460. func validateId(id string) error {
  461. if id == "" {
  462. return fmt.Errorf("Invalid empty id")
  463. }
  464. return nil
  465. }