engine.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package engine
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/dotcloud/docker/utils"
  6. "io"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. )
  13. type Handler func(*Job) Status
  14. var globalHandlers map[string]Handler
  15. func init() {
  16. globalHandlers = make(map[string]Handler)
  17. }
  18. func Register(name string, handler Handler) error {
  19. _, exists := globalHandlers[name]
  20. if exists {
  21. return fmt.Errorf("Can't overwrite global handler for command %s", name)
  22. }
  23. globalHandlers[name] = handler
  24. return nil
  25. }
  26. // The Engine is the core of Docker.
  27. // It acts as a store for *containers*, and allows manipulation of these
  28. // containers by executing *jobs*.
  29. type Engine struct {
  30. root string
  31. handlers map[string]Handler
  32. hack Hack // data for temporary hackery (see hack.go)
  33. id string
  34. Stdout io.Writer
  35. Stderr io.Writer
  36. Stdin io.Reader
  37. }
  38. func (eng *Engine) Root() string {
  39. return eng.root
  40. }
  41. func (eng *Engine) Register(name string, handler Handler) error {
  42. _, exists := eng.handlers[name]
  43. if exists {
  44. return fmt.Errorf("Can't overwrite handler for command %s", name)
  45. }
  46. eng.handlers[name] = handler
  47. return nil
  48. }
  49. // New initializes a new engine managing the directory specified at `root`.
  50. // `root` is used to store containers and any other state private to the engine.
  51. // Changing the contents of the root without executing a job will cause unspecified
  52. // behavior.
  53. func New(root string) (*Engine, error) {
  54. // Check for unsupported architectures
  55. if runtime.GOARCH != "amd64" {
  56. return nil, fmt.Errorf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  57. }
  58. // Check for unsupported kernel versions
  59. // FIXME: it would be cleaner to not test for specific versions, but rather
  60. // test for specific functionalities.
  61. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  62. // without actually causing a kernel panic, so we need this workaround until
  63. // the circumstances of pre-3.8 crashes are clearer.
  64. // For details see http://github.com/dotcloud/docker/issues/407
  65. if k, err := utils.GetKernelVersion(); err != nil {
  66. log.Printf("WARNING: %s\n", err)
  67. } else {
  68. if utils.CompareKernelVersion(k, &utils.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  69. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  70. log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
  71. }
  72. }
  73. }
  74. if err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {
  75. return nil, err
  76. }
  77. // Docker makes some assumptions about the "absoluteness" of root
  78. // ... so let's make sure it has no symlinks
  79. if p, err := filepath.Abs(root); err != nil {
  80. log.Fatalf("Unable to get absolute root (%s): %s", root, err)
  81. } else {
  82. root = p
  83. }
  84. if p, err := filepath.EvalSymlinks(root); err != nil {
  85. log.Fatalf("Unable to canonicalize root (%s): %s", root, err)
  86. } else {
  87. root = p
  88. }
  89. eng := &Engine{
  90. root: root,
  91. handlers: make(map[string]Handler),
  92. id: utils.RandomString(),
  93. Stdout: os.Stdout,
  94. Stderr: os.Stderr,
  95. Stdin: os.Stdin,
  96. }
  97. // Copy existing global handlers
  98. for k, v := range globalHandlers {
  99. eng.handlers[k] = v
  100. }
  101. return eng, nil
  102. }
  103. func (eng *Engine) String() string {
  104. return fmt.Sprintf("%s|%s", eng.Root(), eng.id[:8])
  105. }
  106. // Job creates a new job which can later be executed.
  107. // This function mimics `Command` from the standard os/exec package.
  108. func (eng *Engine) Job(name string, args ...string) *Job {
  109. job := &Job{
  110. Eng: eng,
  111. Name: name,
  112. Args: args,
  113. Stdin: NewInput(),
  114. Stdout: NewOutput(),
  115. Stderr: NewOutput(),
  116. env: &Env{},
  117. }
  118. job.Stderr.Add(utils.NopWriteCloser(eng.Stderr))
  119. handler, exists := eng.handlers[name]
  120. if exists {
  121. job.handler = handler
  122. }
  123. return job
  124. }
  125. // ParseJob creates a new job from a text description using a shell-like syntax.
  126. //
  127. // The following syntax is used to parse `input`:
  128. //
  129. // * Words are separated using standard whitespaces as separators.
  130. // * Quotes and backslashes are not interpreted.
  131. // * Words of the form 'KEY=[VALUE]' are added to the job environment.
  132. // * All other words are added to the job arguments.
  133. //
  134. // For example:
  135. //
  136. // job, _ := eng.ParseJob("VERBOSE=1 echo hello TEST=true world")
  137. //
  138. // The resulting job will have:
  139. // job.Args={"echo", "hello", "world"}
  140. // job.Env={"VERBOSE":"1", "TEST":"true"}
  141. //
  142. func (eng *Engine) ParseJob(input string) (*Job, error) {
  143. // FIXME: use a full-featured command parser
  144. scanner := bufio.NewScanner(strings.NewReader(input))
  145. scanner.Split(bufio.ScanWords)
  146. var (
  147. cmd []string
  148. env Env
  149. )
  150. for scanner.Scan() {
  151. word := scanner.Text()
  152. kv := strings.SplitN(word, "=", 2)
  153. if len(kv) == 2 {
  154. env.Set(kv[0], kv[1])
  155. } else {
  156. cmd = append(cmd, word)
  157. }
  158. }
  159. if len(cmd) == 0 {
  160. return nil, fmt.Errorf("empty command: '%s'", input)
  161. }
  162. job := eng.Job(cmd[0], cmd[1:]...)
  163. job.Env().Init(&env)
  164. return job, nil
  165. }
  166. func (eng *Engine) Logf(format string, args ...interface{}) (n int, err error) {
  167. if os.Getenv("TEST") == "" {
  168. prefixedFormat := fmt.Sprintf("[%s] %s\n", eng, strings.TrimRight(format, "\n"))
  169. return fmt.Fprintf(eng.Stderr, prefixedFormat, args...)
  170. }
  171. return 0, nil
  172. }