utils_test.go 9.7 KB

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