utils_test.go 9.8 KB

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