utils_test.go 9.8 KB

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