container.go 12 KB

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