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