container.go 12 KB

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