runtime_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/utils"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "testing"
  15. "time"
  16. )
  17. const (
  18. unitTestImageName = "docker-unit-tests"
  19. unitTestImageId = "e9aa60c60128cad1"
  20. unitTestStoreBase = "/var/lib/docker/unit-tests"
  21. testDaemonAddr = "127.0.0.1:4270"
  22. testDaemonProto = "tcp"
  23. )
  24. var globalRuntime *Runtime
  25. func nuke(runtime *Runtime) error {
  26. var wg sync.WaitGroup
  27. for _, container := range runtime.List() {
  28. wg.Add(1)
  29. go func(c *Container) {
  30. c.Kill()
  31. wg.Done()
  32. }(container)
  33. }
  34. wg.Wait()
  35. return os.RemoveAll(runtime.root)
  36. }
  37. func cleanup(runtime *Runtime) error {
  38. for _, container := range runtime.List() {
  39. container.Kill()
  40. runtime.Destroy(container)
  41. }
  42. images, err := runtime.graph.All()
  43. if err != nil {
  44. return err
  45. }
  46. for _, image := range images {
  47. if image.ID != unitTestImageId {
  48. runtime.graph.Delete(image.ID)
  49. }
  50. }
  51. return nil
  52. }
  53. func layerArchive(tarfile string) (io.Reader, error) {
  54. // FIXME: need to close f somewhere
  55. f, err := os.Open(tarfile)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return f, nil
  60. }
  61. func init() {
  62. // Hack to run sys init during unit testing
  63. if utils.SelfPath() == "/sbin/init" {
  64. SysInit()
  65. return
  66. }
  67. if uid := syscall.Geteuid(); uid != 0 {
  68. log.Fatal("docker tests needs to be run as root")
  69. }
  70. NetworkBridgeIface = "testdockbr0"
  71. // Make it our Store root
  72. runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, false)
  73. if err != nil {
  74. panic(err)
  75. }
  76. globalRuntime = runtime
  77. // Create the "Server"
  78. srv := &Server{
  79. runtime: runtime,
  80. enableCors: false,
  81. lock: &sync.Mutex{},
  82. pullingPool: make(map[string]struct{}),
  83. pushingPool: make(map[string]struct{}),
  84. }
  85. // Retrieve the Image
  86. if err := srv.ImagePull(unitTestImageName, "", "", os.Stdout, utils.NewStreamFormatter(false), nil); err != nil {
  87. panic(err)
  88. }
  89. // Spawn a Daemon
  90. go func() {
  91. if err := ListenAndServe(testDaemonProto, testDaemonAddr, srv, os.Getenv("DEBUG") != ""); err != nil {
  92. panic(err)
  93. }
  94. }()
  95. // Give some time to ListenAndServer to actually start
  96. time.Sleep(time.Second)
  97. }
  98. // FIXME: test that ImagePull(json=true) send correct json output
  99. func newTestRuntime() (*Runtime, error) {
  100. root, err := ioutil.TempDir("", "docker-test")
  101. if err != nil {
  102. return nil, err
  103. }
  104. if err := os.Remove(root); err != nil {
  105. return nil, err
  106. }
  107. if err := utils.CopyDirectory(unitTestStoreBase, root); err != nil {
  108. return nil, err
  109. }
  110. runtime, err := NewRuntimeFromDirectory(root, false)
  111. if err != nil {
  112. return nil, err
  113. }
  114. runtime.UpdateCapabilities(true)
  115. return runtime, nil
  116. }
  117. func GetTestImage(runtime *Runtime) *Image {
  118. imgs, err := runtime.graph.All()
  119. if err != nil {
  120. panic(err)
  121. }
  122. for i := range imgs {
  123. if imgs[i].ID == unitTestImageId {
  124. return imgs[i]
  125. }
  126. }
  127. panic(fmt.Errorf("Test image %v not found", unitTestImageId))
  128. }
  129. func TestRuntimeCreate(t *testing.T) {
  130. runtime, err := newTestRuntime()
  131. if err != nil {
  132. t.Fatal(err)
  133. }
  134. defer nuke(runtime)
  135. // Make sure we start we 0 containers
  136. if len(runtime.List()) != 0 {
  137. t.Errorf("Expected 0 containers, %v found", len(runtime.List()))
  138. }
  139. builder := NewBuilder(runtime)
  140. container, err := builder.Create(&Config{
  141. Image: GetTestImage(runtime).ID,
  142. Cmd: []string{"ls", "-al"},
  143. },
  144. )
  145. if err != nil {
  146. t.Fatal(err)
  147. }
  148. defer func() {
  149. if err := runtime.Destroy(container); err != nil {
  150. t.Error(err)
  151. }
  152. }()
  153. // Make sure we can find the newly created container with List()
  154. if len(runtime.List()) != 1 {
  155. t.Errorf("Expected 1 container, %v found", len(runtime.List()))
  156. }
  157. // Make sure the container List() returns is the right one
  158. if runtime.List()[0].ID != container.ID {
  159. t.Errorf("Unexpected container %v returned by List", runtime.List()[0])
  160. }
  161. // Make sure we can get the container with Get()
  162. if runtime.Get(container.ID) == nil {
  163. t.Errorf("Unable to get newly created container")
  164. }
  165. // Make sure it is the right container
  166. if runtime.Get(container.ID) != container {
  167. t.Errorf("Get() returned the wrong container")
  168. }
  169. // Make sure Exists returns it as existing
  170. if !runtime.Exists(container.ID) {
  171. t.Errorf("Exists() returned false for a newly created container")
  172. }
  173. // Make sure crete with bad parameters returns an error
  174. _, err = builder.Create(
  175. &Config{
  176. Image: GetTestImage(runtime).ID,
  177. },
  178. )
  179. if err == nil {
  180. t.Fatal("Builder.Create should throw an error when Cmd is missing")
  181. }
  182. _, err = builder.Create(
  183. &Config{
  184. Image: GetTestImage(runtime).ID,
  185. Cmd: []string{},
  186. },
  187. )
  188. if err == nil {
  189. t.Fatal("Builder.Create should throw an error when Cmd is empty")
  190. }
  191. }
  192. func TestDestroy(t *testing.T) {
  193. runtime, err := newTestRuntime()
  194. if err != nil {
  195. t.Fatal(err)
  196. }
  197. defer nuke(runtime)
  198. container, err := NewBuilder(runtime).Create(&Config{
  199. Image: GetTestImage(runtime).ID,
  200. Cmd: []string{"ls", "-al"},
  201. },
  202. )
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. // Destroy
  207. if err := runtime.Destroy(container); err != nil {
  208. t.Error(err)
  209. }
  210. // Make sure runtime.Exists() behaves correctly
  211. if runtime.Exists("test_destroy") {
  212. t.Errorf("Exists() returned true")
  213. }
  214. // Make sure runtime.List() doesn't list the destroyed container
  215. if len(runtime.List()) != 0 {
  216. t.Errorf("Expected 0 container, %v found", len(runtime.List()))
  217. }
  218. // Make sure runtime.Get() refuses to return the unexisting container
  219. if runtime.Get(container.ID) != nil {
  220. t.Errorf("Unable to get newly created container")
  221. }
  222. // Make sure the container root directory does not exist anymore
  223. _, err = os.Stat(container.root)
  224. if err == nil || !os.IsNotExist(err) {
  225. t.Errorf("Container root directory still exists after destroy")
  226. }
  227. // Test double destroy
  228. if err := runtime.Destroy(container); err == nil {
  229. // It should have failed
  230. t.Errorf("Double destroy did not fail")
  231. }
  232. }
  233. func TestGet(t *testing.T) {
  234. runtime, err := newTestRuntime()
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. defer nuke(runtime)
  239. builder := NewBuilder(runtime)
  240. container1, err := builder.Create(&Config{
  241. Image: GetTestImage(runtime).ID,
  242. Cmd: []string{"ls", "-al"},
  243. },
  244. )
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. defer runtime.Destroy(container1)
  249. container2, err := builder.Create(&Config{
  250. Image: GetTestImage(runtime).ID,
  251. Cmd: []string{"ls", "-al"},
  252. },
  253. )
  254. if err != nil {
  255. t.Fatal(err)
  256. }
  257. defer runtime.Destroy(container2)
  258. container3, err := builder.Create(&Config{
  259. Image: GetTestImage(runtime).ID,
  260. Cmd: []string{"ls", "-al"},
  261. },
  262. )
  263. if err != nil {
  264. t.Fatal(err)
  265. }
  266. defer runtime.Destroy(container3)
  267. if runtime.Get(container1.ID) != container1 {
  268. t.Errorf("Get(test1) returned %v while expecting %v", runtime.Get(container1.ID), container1)
  269. }
  270. if runtime.Get(container2.ID) != container2 {
  271. t.Errorf("Get(test2) returned %v while expecting %v", runtime.Get(container2.ID), container2)
  272. }
  273. if runtime.Get(container3.ID) != container3 {
  274. t.Errorf("Get(test3) returned %v while expecting %v", runtime.Get(container3.ID), container3)
  275. }
  276. }
  277. func findAvailalblePort(runtime *Runtime, port int) (*Container, error) {
  278. strPort := strconv.Itoa(port)
  279. container, err := NewBuilder(runtime).Create(&Config{
  280. Image: GetTestImage(runtime).ID,
  281. Cmd: []string{"sh", "-c", "echo well hello there | nc -l -p " + strPort},
  282. PortSpecs: []string{strPort},
  283. },
  284. )
  285. if err != nil {
  286. return nil, err
  287. }
  288. hostConfig := &HostConfig{}
  289. if err := container.Start(hostConfig); err != nil {
  290. if strings.Contains(err.Error(), "address already in use") {
  291. return nil, nil
  292. }
  293. return nil, err
  294. }
  295. return container, nil
  296. }
  297. // Run a container with a TCP port allocated, and test that it can receive connections on localhost
  298. func TestAllocatePortLocalhost(t *testing.T) {
  299. runtime, err := newTestRuntime()
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. port := 5554
  304. var container *Container
  305. for {
  306. port += 1
  307. log.Println("Trying port", port)
  308. t.Log("Trying port", port)
  309. container, err = findAvailalblePort(runtime, port)
  310. if container != nil {
  311. break
  312. }
  313. if err != nil {
  314. t.Fatal(err)
  315. }
  316. log.Println("Port", port, "already in use")
  317. t.Log("Port", port, "already in use")
  318. }
  319. defer container.Kill()
  320. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  321. for {
  322. if container.State.Running {
  323. break
  324. }
  325. time.Sleep(10 * time.Millisecond)
  326. }
  327. })
  328. conn, err := net.Dial("tcp",
  329. fmt.Sprintf(
  330. "localhost:%s", container.NetworkSettings.PortMapping[strconv.Itoa(port)],
  331. ),
  332. )
  333. if err != nil {
  334. t.Fatal(err)
  335. }
  336. defer conn.Close()
  337. output, err := ioutil.ReadAll(conn)
  338. if err != nil {
  339. t.Fatal(err)
  340. }
  341. if string(output) != "well hello there\n" {
  342. t.Fatalf("Received wrong output from network connection: should be '%s', not '%s'",
  343. "well hello there\n",
  344. string(output),
  345. )
  346. }
  347. container.Wait()
  348. }
  349. func TestRestore(t *testing.T) {
  350. root, err := ioutil.TempDir("", "docker-test")
  351. if err != nil {
  352. t.Fatal(err)
  353. }
  354. if err := os.Remove(root); err != nil {
  355. t.Fatal(err)
  356. }
  357. if err := utils.CopyDirectory(unitTestStoreBase, root); err != nil {
  358. t.Fatal(err)
  359. }
  360. runtime1, err := NewRuntimeFromDirectory(root, false)
  361. if err != nil {
  362. t.Fatal(err)
  363. }
  364. builder := NewBuilder(runtime1)
  365. // Create a container with one instance of docker
  366. container1, err := builder.Create(&Config{
  367. Image: GetTestImage(runtime1).ID,
  368. Cmd: []string{"ls", "-al"},
  369. },
  370. )
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. defer runtime1.Destroy(container1)
  375. // Create a second container meant to be killed
  376. container2, err := builder.Create(&Config{
  377. Image: GetTestImage(runtime1).ID,
  378. Cmd: []string{"/bin/cat"},
  379. OpenStdin: true,
  380. },
  381. )
  382. if err != nil {
  383. t.Fatal(err)
  384. }
  385. defer runtime1.Destroy(container2)
  386. // Start the container non blocking
  387. hostConfig := &HostConfig{}
  388. if err := container2.Start(hostConfig); err != nil {
  389. t.Fatal(err)
  390. }
  391. if !container2.State.Running {
  392. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  393. }
  394. // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running'
  395. cStdin, _ := container2.StdinPipe()
  396. cStdin.Close()
  397. if err := container2.WaitTimeout(2 * time.Second); err != nil {
  398. t.Fatal(err)
  399. }
  400. container2.State.Running = true
  401. container2.ToDisk()
  402. if len(runtime1.List()) != 2 {
  403. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  404. }
  405. if err := container1.Run(); err != nil {
  406. t.Fatal(err)
  407. }
  408. if !container2.State.Running {
  409. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  410. }
  411. // Here are are simulating a docker restart - that is, reloading all containers
  412. // from scratch
  413. runtime2, err := NewRuntimeFromDirectory(root, false)
  414. if err != nil {
  415. t.Fatal(err)
  416. }
  417. defer nuke(runtime2)
  418. if len(runtime2.List()) != 2 {
  419. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  420. }
  421. runningCount := 0
  422. for _, c := range runtime2.List() {
  423. if c.State.Running {
  424. t.Errorf("Running container found: %v (%v)", c.ID, c.Path)
  425. runningCount++
  426. }
  427. }
  428. if runningCount != 0 {
  429. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  430. }
  431. container3 := runtime2.Get(container1.ID)
  432. if container3 == nil {
  433. t.Fatal("Unable to Get container")
  434. }
  435. if err := container3.Run(); err != nil {
  436. t.Fatal(err)
  437. }
  438. container2.State.Running = false
  439. }