utils_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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/daemon/networkdriver/bridge"
  20. "github.com/docker/docker/engine"
  21. "github.com/docker/docker/graph"
  22. flag "github.com/docker/docker/pkg/mflag"
  23. "github.com/docker/docker/registry"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/docker/utils"
  26. )
  27. type Fataler interface {
  28. Fatal(...interface{})
  29. }
  30. // This file contains utility functions for docker's unit test suite.
  31. // It has to be named XXX_test.go, apparently, in other to access private functions
  32. // from other XXX_test.go functions.
  33. // Create a temporary daemon suitable for unit testing.
  34. // Call t.Fatal() at the first error.
  35. func mkDaemon(f Fataler) *daemon.Daemon {
  36. eng := newTestEngine(f, false, "")
  37. return mkDaemonFromEngine(eng, f)
  38. }
  39. func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f Fataler, name string) (shortId string) {
  40. env := new(engine.Env)
  41. if err := env.Import(config); err != nil {
  42. f.Fatal(err)
  43. }
  44. containerId, _, err := getDaemon(eng).ContainerCreate(name, env)
  45. if err != nil {
  46. f.Fatal(err)
  47. }
  48. return containerId
  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. env := new(engine.Env)
  55. if err := getDaemon(eng).ContainerStart(id, env); 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 := getDaemon(eng).ContainerKill(id, 0); 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. Bridge: bridge.Config{
  166. InterContainerCommunication: true,
  167. },
  168. TrustKeyPath: filepath.Join(root, "key.json"),
  169. LogConfig: runconfig.LogConfig{Type: "json-file"},
  170. }
  171. d, err := daemon.NewDaemon(cfg, eng, registry.NewService(nil))
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. if err := d.Install(eng); err != nil {
  176. t.Fatal(err)
  177. }
  178. return eng
  179. }
  180. func NewTestEngine(t Fataler) *engine.Engine {
  181. return newTestEngine(t, false, "")
  182. }
  183. func newTestDirectory(templateDir string) (dir string, err error) {
  184. return utils.TestDirectory(templateDir)
  185. }
  186. func getCallerName(depth int) string {
  187. return utils.GetCallerName(depth)
  188. }
  189. // Write `content` to the file at path `dst`, creating it if necessary,
  190. // as well as any missing directories.
  191. // The file is truncated if it already exists.
  192. // Call t.Fatal() at the first error.
  193. func writeFile(dst, content string, t *testing.T) {
  194. // Create subdirectories if necessary
  195. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  196. t.Fatal(err)
  197. }
  198. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. // Write content (truncate if it exists)
  203. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  204. t.Fatal(err)
  205. }
  206. }
  207. // Return the contents of file at path `src`.
  208. // Call t.Fatal() at the first error (including if the file doesn't exist)
  209. func readFile(src string, t *testing.T) (content string) {
  210. f, err := os.Open(src)
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. data, err := ioutil.ReadAll(f)
  215. if err != nil {
  216. t.Fatal(err)
  217. }
  218. return string(data)
  219. }
  220. // Create a test container from the given daemon `r` and run arguments `args`.
  221. // If the image name is "_", (eg. []string{"-i", "-t", "_", "bash"}, it is
  222. // dynamically replaced by the current test image.
  223. // The caller is responsible for destroying the container.
  224. // Call t.Fatal() at the first error.
  225. func mkContainer(r *daemon.Daemon, args []string, t *testing.T) (*daemon.Container, *runconfig.HostConfig, error) {
  226. config, hc, _, err := parseRun(args)
  227. defer func() {
  228. if err != nil && t != nil {
  229. t.Fatal(err)
  230. }
  231. }()
  232. if err != nil {
  233. return nil, nil, err
  234. }
  235. if config.Image == "_" {
  236. config.Image = GetTestImage(r).ID
  237. }
  238. c, _, err := r.Create(config, nil, "")
  239. if err != nil {
  240. return nil, nil, err
  241. }
  242. // NOTE: hostConfig is ignored.
  243. // If `args` specify privileged mode, custom lxc conf, external mount binds,
  244. // port redirects etc. they will be ignored.
  245. // This is because the correct way to set these things is to pass environment
  246. // to the `start` job.
  247. // FIXME: this helper function should be deprecated in favor of calling
  248. // `create` and `start` jobs directly.
  249. return c, hc, nil
  250. }
  251. // Create a test container, start it, wait for it to complete, destroy it,
  252. // and return its standard output as a string.
  253. // The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image.
  254. // If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally.
  255. func runContainer(eng *engine.Engine, r *daemon.Daemon, args []string, t *testing.T) (output string, err error) {
  256. defer func() {
  257. if err != nil && t != nil {
  258. t.Fatal(err)
  259. }
  260. }()
  261. container, hc, err := mkContainer(r, args, t)
  262. if err != nil {
  263. return "", err
  264. }
  265. defer r.Rm(container)
  266. stdout := container.StdoutPipe()
  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 getImages(eng *engine.Engine, t *testing.T, all bool, filter string) []*types.Image {
  301. config := graph.ImagesConfig{
  302. Filter: filter,
  303. All: all,
  304. }
  305. images, err := getDaemon(eng).Repositories().Images(&config)
  306. if err != nil {
  307. t.Fatal(err)
  308. }
  309. return images
  310. }
  311. func parseRun(args []string) (*runconfig.Config, *runconfig.HostConfig, *flag.FlagSet, error) {
  312. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  313. cmd.SetOutput(ioutil.Discard)
  314. cmd.Usage = nil
  315. return runconfig.Parse(cmd, args)
  316. }
  317. func getDaemon(eng *engine.Engine) *daemon.Daemon {
  318. return eng.HackGetGlobalVar("httpapi.daemon").(*daemon.Daemon)
  319. }