utils_test.go 9.8 KB

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