utils_test.go 9.6 KB

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