engine.go 5.6 KB

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