engine.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package engine
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/dotcloud/docker/utils"
  6. "io"
  7. "log"
  8. "os"
  9. "runtime"
  10. "sort"
  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. func unregister(name string) {
  27. delete(globalHandlers, name)
  28. }
  29. // The Engine is the core of Docker.
  30. // It acts as a store for *containers*, and allows manipulation of these
  31. // containers by executing *jobs*.
  32. type Engine struct {
  33. root string
  34. handlers map[string]Handler
  35. hack Hack // data for temporary hackery (see hack.go)
  36. id string
  37. Stdout io.Writer
  38. Stderr io.Writer
  39. Stdin io.Reader
  40. Logging bool
  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. eng := &Engine{
  82. root: root,
  83. handlers: make(map[string]Handler),
  84. id: utils.RandomString(),
  85. Stdout: os.Stdout,
  86. Stderr: os.Stderr,
  87. Stdin: os.Stdin,
  88. Logging: true,
  89. }
  90. eng.Register("commands", func(job *Job) Status {
  91. for _, name := range eng.commands() {
  92. job.Printf("%s\n", name)
  93. }
  94. return StatusOK
  95. })
  96. // Copy existing global handlers
  97. for k, v := range globalHandlers {
  98. eng.handlers[k] = v
  99. }
  100. return eng, nil
  101. }
  102. func (eng *Engine) String() string {
  103. return fmt.Sprintf("%s|%s", eng.Root(), eng.id[:8])
  104. }
  105. // Commands returns a list of all currently registered commands,
  106. // sorted alphabetically.
  107. func (eng *Engine) commands() []string {
  108. names := make([]string, 0, len(eng.handlers))
  109. for name := range eng.handlers {
  110. names = append(names, name)
  111. }
  112. sort.Strings(names)
  113. return names
  114. }
  115. // Job creates a new job which can later be executed.
  116. // This function mimics `Command` from the standard os/exec package.
  117. func (eng *Engine) Job(name string, args ...string) *Job {
  118. job := &Job{
  119. Eng: eng,
  120. Name: name,
  121. Args: args,
  122. Stdin: NewInput(),
  123. Stdout: NewOutput(),
  124. Stderr: NewOutput(),
  125. env: &Env{},
  126. }
  127. if eng.Logging {
  128. job.Stderr.Add(utils.NopWriteCloser(eng.Stderr))
  129. }
  130. handler, exists := eng.handlers[name]
  131. if exists {
  132. job.handler = handler
  133. }
  134. return job
  135. }
  136. // ParseJob creates a new job from a text description using a shell-like syntax.
  137. //
  138. // The following syntax is used to parse `input`:
  139. //
  140. // * Words are separated using standard whitespaces as separators.
  141. // * Quotes and backslashes are not interpreted.
  142. // * Words of the form 'KEY=[VALUE]' are added to the job environment.
  143. // * All other words are added to the job arguments.
  144. //
  145. // For example:
  146. //
  147. // job, _ := eng.ParseJob("VERBOSE=1 echo hello TEST=true world")
  148. //
  149. // The resulting job will have:
  150. // job.Args={"echo", "hello", "world"}
  151. // job.Env={"VERBOSE":"1", "TEST":"true"}
  152. //
  153. func (eng *Engine) ParseJob(input string) (*Job, error) {
  154. // FIXME: use a full-featured command parser
  155. scanner := bufio.NewScanner(strings.NewReader(input))
  156. scanner.Split(bufio.ScanWords)
  157. var (
  158. cmd []string
  159. env Env
  160. )
  161. for scanner.Scan() {
  162. word := scanner.Text()
  163. kv := strings.SplitN(word, "=", 2)
  164. if len(kv) == 2 {
  165. env.Set(kv[0], kv[1])
  166. } else {
  167. cmd = append(cmd, word)
  168. }
  169. }
  170. if len(cmd) == 0 {
  171. return nil, fmt.Errorf("empty command: '%s'", input)
  172. }
  173. job := eng.Job(cmd[0], cmd[1:]...)
  174. job.Env().Init(&env)
  175. return job, nil
  176. }
  177. func (eng *Engine) Logf(format string, args ...interface{}) (n int, err error) {
  178. if !eng.Logging {
  179. return 0, nil
  180. }
  181. prefixedFormat := fmt.Sprintf("[%s] %s\n", eng, strings.TrimRight(format, "\n"))
  182. return fmt.Fprintf(eng.Stderr, prefixedFormat, args...)
  183. }