utils_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package docker
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  16. "github.com/docker/docker/builtins"
  17. "github.com/docker/docker/daemon"
  18. "github.com/docker/docker/engine"
  19. flag "github.com/docker/docker/pkg/mflag"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/docker/utils"
  22. )
  23. type Fataler interface {
  24. Fatal(...interface{})
  25. }
  26. // This file contains utility functions for docker's unit test suite.
  27. // It has to be named XXX_test.go, apparently, in other to access private functions
  28. // from other XXX_test.go functions.
  29. // Create a temporary daemon suitable for unit testing.
  30. // Call t.Fatal() at the first error.
  31. func mkDaemon(f Fataler) *daemon.Daemon {
  32. eng := newTestEngine(f, false, "")
  33. return mkDaemonFromEngine(eng, f)
  34. }
  35. func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f Fataler, name string) (shortId string) {
  36. job := eng.Job("create", name)
  37. if err := job.ImportEnv(config); err != nil {
  38. f.Fatal(err)
  39. }
  40. var outputBuffer = bytes.NewBuffer(nil)
  41. job.Stdout.Add(outputBuffer)
  42. if err := job.Run(); err != nil {
  43. f.Fatal(err)
  44. }
  45. return engine.Tail(outputBuffer, 1)
  46. }
  47. func createTestContainer(eng *engine.Engine, config *runconfig.Config, f Fataler) (shortId string) {
  48. return createNamedTestContainer(eng, config, f, "")
  49. }
  50. func startContainer(eng *engine.Engine, id string, t Fataler) {
  51. job := eng.Job("start", id)
  52. if err := job.Run(); err != nil {
  53. t.Fatal(err)
  54. }
  55. }
  56. func containerRun(eng *engine.Engine, id string, t Fataler) {
  57. startContainer(eng, id, t)
  58. containerWait(eng, id, t)
  59. }
  60. func containerFileExists(eng *engine.Engine, id, dir string, t Fataler) bool {
  61. c := getContainer(eng, id, t)
  62. if err := c.Mount(); err != nil {
  63. t.Fatal(err)
  64. }
  65. defer c.Unmount()
  66. if _, err := os.Stat(path.Join(c.RootfsPath(), dir)); err != nil {
  67. if os.IsNotExist(err) {
  68. return false
  69. }
  70. t.Fatal(err)
  71. }
  72. return true
  73. }
  74. func containerAttach(eng *engine.Engine, id string, t Fataler) (io.WriteCloser, io.ReadCloser) {
  75. c := getContainer(eng, id, t)
  76. i := c.StdinPipe()
  77. o := c.StdoutPipe()
  78. return i, o
  79. }
  80. func containerWait(eng *engine.Engine, id string, t Fataler) int {
  81. ex, _ := getContainer(eng, id, t).WaitStop(-1 * time.Second)
  82. return ex
  83. }
  84. func containerWaitTimeout(eng *engine.Engine, id string, t Fataler) error {
  85. _, err := getContainer(eng, id, t).WaitStop(500 * time.Millisecond)
  86. return err
  87. }
  88. func containerKill(eng *engine.Engine, id string, t Fataler) {
  89. if err := eng.Job("kill", id).Run(); err != nil {
  90. t.Fatal(err)
  91. }
  92. }
  93. func containerRunning(eng *engine.Engine, id string, t Fataler) bool {
  94. return getContainer(eng, id, t).IsRunning()
  95. }
  96. func containerAssertExists(eng *engine.Engine, id string, t Fataler) {
  97. getContainer(eng, id, t)
  98. }
  99. func containerAssertNotExists(eng *engine.Engine, id string, t Fataler) {
  100. daemon := mkDaemonFromEngine(eng, t)
  101. if c := daemon.Get(id); c != nil {
  102. t.Fatal(fmt.Errorf("Container %s should not exist", id))
  103. }
  104. }
  105. // assertHttpNotError expect the given response to not have an error.
  106. // Otherwise the it causes the test to fail.
  107. func assertHttpNotError(r *httptest.ResponseRecorder, t Fataler) {
  108. // Non-error http status are [200, 400)
  109. if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest {
  110. t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code))
  111. }
  112. }
  113. // assertHttpError expect the given response to have an error.
  114. // Otherwise the it causes the test to fail.
  115. func assertHttpError(r *httptest.ResponseRecorder, t Fataler) {
  116. // Non-error http status are [200, 400)
  117. if !(r.Code < http.StatusOK || r.Code >= http.StatusBadRequest) {
  118. t.Fatal(fmt.Errorf("Unexpected http success code: %v", r.Code))
  119. }
  120. }
  121. func getContainer(eng *engine.Engine, id string, t Fataler) *daemon.Container {
  122. daemon := mkDaemonFromEngine(eng, t)
  123. c := daemon.Get(id)
  124. if c == nil {
  125. t.Fatal(fmt.Errorf("No such container: %s", id))
  126. }
  127. return c
  128. }
  129. func mkDaemonFromEngine(eng *engine.Engine, t Fataler) *daemon.Daemon {
  130. iDaemon := eng.Hack_GetGlobalVar("httpapi.daemon")
  131. if iDaemon == nil {
  132. panic("Legacy daemon field not set in engine")
  133. }
  134. daemon, ok := iDaemon.(*daemon.Daemon)
  135. if !ok {
  136. panic("Legacy daemon field in engine does not cast to *daemon.Daemon")
  137. }
  138. return daemon
  139. }
  140. func newTestEngine(t Fataler, autorestart bool, root string) *engine.Engine {
  141. if root == "" {
  142. if dir, err := newTestDirectory(unitTestStoreBase); err != nil {
  143. t.Fatal(err)
  144. } else {
  145. root = dir
  146. }
  147. }
  148. os.MkdirAll(root, 0700)
  149. eng := engine.New()
  150. eng.Logging = false
  151. // Load default plugins
  152. builtins.Register(eng)
  153. // (This is manually copied and modified from main() until we have a more generic plugin system)
  154. cfg := &daemon.Config{
  155. Root: root,
  156. AutoRestart: autorestart,
  157. ExecDriver: "native",
  158. // Either InterContainerCommunication or EnableIptables must be set,
  159. // otherwise NewDaemon will fail because of conflicting settings.
  160. InterContainerCommunication: true,
  161. TrustKeyPath: filepath.Join(root, "key.json"),
  162. }
  163. d, err := daemon.NewDaemon(cfg, eng)
  164. if err != nil {
  165. t.Fatal(err)
  166. }
  167. if err := d.Install(eng); err != nil {
  168. t.Fatal(err)
  169. }
  170. return eng
  171. }
  172. func NewTestEngine(t Fataler) *engine.Engine {
  173. return newTestEngine(t, false, "")
  174. }
  175. func newTestDirectory(templateDir string) (dir string, err error) {
  176. return utils.TestDirectory(templateDir)
  177. }
  178. func getCallerName(depth int) string {
  179. return utils.GetCallerName(depth)
  180. }
  181. // Write `content` to the file at path `dst`, creating it if necessary,
  182. // as well as any missing directories.
  183. // The file is truncated if it already exists.
  184. // Call t.Fatal() at the first error.
  185. func writeFile(dst, content string, t *testing.T) {
  186. // Create subdirectories if necessary
  187. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  188. t.Fatal(err)
  189. }
  190. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  191. if err != nil {
  192. t.Fatal(err)
  193. }
  194. // Write content (truncate if it exists)
  195. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  196. t.Fatal(err)
  197. }
  198. }
  199. // Return the contents of file at path `src`.
  200. // Call t.Fatal() at the first error (including if the file doesn't exist)
  201. func readFile(src string, t *testing.T) (content string) {
  202. f, err := os.Open(src)
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. data, err := ioutil.ReadAll(f)
  207. if err != nil {
  208. t.Fatal(err)
  209. }
  210. return string(data)
  211. }
  212. // Create a test container from the given daemon `r` and run arguments `args`.
  213. // If the image name is "_", (eg. []string{"-i", "-t", "_", "bash"}, it is
  214. // dynamically replaced by the current test image.
  215. // The caller is responsible for destroying the container.
  216. // Call t.Fatal() at the first error.
  217. func mkContainer(r *daemon.Daemon, args []string, t *testing.T) (*daemon.Container, *runconfig.HostConfig, error) {
  218. config, hc, _, err := parseRun(args)
  219. defer func() {
  220. if err != nil && t != nil {
  221. t.Fatal(err)
  222. }
  223. }()
  224. if err != nil {
  225. return nil, nil, err
  226. }
  227. if config.Image == "_" {
  228. config.Image = GetTestImage(r).ID
  229. }
  230. c, _, err := r.Create(config, nil, "")
  231. if err != nil {
  232. return nil, nil, err
  233. }
  234. // NOTE: hostConfig is ignored.
  235. // If `args` specify privileged mode, custom lxc conf, external mount binds,
  236. // port redirects etc. they will be ignored.
  237. // This is because the correct way to set these things is to pass environment
  238. // to the `start` job.
  239. // FIXME: this helper function should be deprecated in favor of calling
  240. // `create` and `start` jobs directly.
  241. return c, hc, nil
  242. }
  243. // Create a test container, start it, wait for it to complete, destroy it,
  244. // and return its standard output as a string.
  245. // The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image.
  246. // If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally.
  247. func runContainer(eng *engine.Engine, r *daemon.Daemon, args []string, t *testing.T) (output string, err error) {
  248. defer func() {
  249. if err != nil && t != nil {
  250. t.Fatal(err)
  251. }
  252. }()
  253. container, hc, err := mkContainer(r, args, t)
  254. if err != nil {
  255. return "", err
  256. }
  257. defer r.Destroy(container)
  258. stdout := container.StdoutPipe()
  259. defer stdout.Close()
  260. job := eng.Job("start", container.ID)
  261. if err := job.ImportEnv(hc); err != nil {
  262. return "", err
  263. }
  264. if err := job.Run(); err != nil {
  265. return "", err
  266. }
  267. container.WaitStop(-1 * time.Second)
  268. data, err := ioutil.ReadAll(stdout)
  269. if err != nil {
  270. return "", err
  271. }
  272. output = string(data)
  273. return
  274. }
  275. // FIXME: this is duplicated from graph_test.go in the docker package.
  276. func fakeTar() (io.ReadCloser, error) {
  277. content := []byte("Hello world!\n")
  278. buf := new(bytes.Buffer)
  279. tw := tar.NewWriter(buf)
  280. for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} {
  281. hdr := new(tar.Header)
  282. hdr.Size = int64(len(content))
  283. hdr.Name = name
  284. if err := tw.WriteHeader(hdr); err != nil {
  285. return nil, err
  286. }
  287. tw.Write([]byte(content))
  288. }
  289. tw.Close()
  290. return ioutil.NopCloser(buf), nil
  291. }
  292. func getAllImages(eng *engine.Engine, t *testing.T) *engine.Table {
  293. return getImages(eng, t, true, "")
  294. }
  295. func getImages(eng *engine.Engine, t *testing.T, all bool, filter string) *engine.Table {
  296. job := eng.Job("images")
  297. job.SetenvBool("all", all)
  298. job.Setenv("filter", filter)
  299. images, err := job.Stdout.AddListTable()
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. if err := job.Run(); err != nil {
  304. t.Fatal(err)
  305. }
  306. return images
  307. }
  308. func parseRun(args []string) (*runconfig.Config, *runconfig.HostConfig, *flag.FlagSet, error) {
  309. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  310. cmd.SetOutput(ioutil.Discard)
  311. cmd.Usage = nil
  312. return runconfig.Parse(cmd, args)
  313. }