runtime_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. package docker
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/dotcloud/docker/devmapper"
  6. "github.com/dotcloud/docker/utils"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "syscall"
  19. "testing"
  20. "time"
  21. )
  22. const (
  23. unitTestImageName = "docker-test-image"
  24. unitTestImageID = "83599e29c455eb719f77d799bc7c51521b9551972f5a850d7ad265bc1b5292f6" // 1.0
  25. unitTestNetworkBridge = "testdockbr0"
  26. unitTestStoreBase = "/var/lib/docker/unit-tests"
  27. testDaemonAddr = "127.0.0.1:4270"
  28. testDaemonProto = "tcp"
  29. unitTestDMDataLoopbackSize = 209715200 // 200MB
  30. unitTestDMMetaDataLoopbackSize = 104857600 // 100MB
  31. unitTestDMBaseFsSize = 157286400 // 150MB
  32. )
  33. var (
  34. globalRuntime *Runtime
  35. startFds int
  36. startGoroutines int
  37. )
  38. func nuke(runtime *Runtime) error {
  39. var wg sync.WaitGroup
  40. for _, container := range runtime.List() {
  41. wg.Add(1)
  42. go func(c *Container) {
  43. c.Kill()
  44. wg.Done()
  45. }(container)
  46. }
  47. wg.Wait()
  48. runtime.networkManager.Close()
  49. for _, container := range runtime.List() {
  50. container.EnsureUnmounted()
  51. }
  52. if err := runtime.deviceSet.Shutdown(); err != nil {
  53. utils.Debugf("Error shutting down devicemapper for runtime %s", runtime.root)
  54. }
  55. return os.RemoveAll(runtime.root)
  56. }
  57. func cleanup(runtime *Runtime) error {
  58. for _, container := range runtime.List() {
  59. container.Kill()
  60. runtime.Destroy(container)
  61. }
  62. images, err := runtime.graph.Map()
  63. if err != nil {
  64. return err
  65. }
  66. for _, image := range images {
  67. if image.ID != unitTestImageID {
  68. runtime.DeleteImage(image.ID)
  69. }
  70. }
  71. return nil
  72. }
  73. func layerArchive(tarfile string) (io.Reader, error) {
  74. // FIXME: need to close f somewhere
  75. f, err := os.Open(tarfile)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return f, nil
  80. }
  81. // Remove any leftover device mapper devices from earlier runs of the unit tests
  82. func removeDev(name string) error {
  83. path := filepath.Join("/dev/mapper", name)
  84. if f, err := os.OpenFile(path, os.O_RDONLY, 07777); err != nil {
  85. if er, ok := err.(*os.PathError); ok && er.Err == syscall.ENXIO {
  86. // No device for this node, just remove it
  87. return os.Remove(path)
  88. }
  89. } else {
  90. f.Close()
  91. }
  92. if err := devmapper.RemoveDevice(name); err != nil {
  93. return fmt.Errorf("Unable to remove device %s needed to get a freash unit test environment", name)
  94. }
  95. return nil
  96. }
  97. func cleanupDevMapper() error {
  98. utils.Debugf("[devmapper cleanup] starting")
  99. defer utils.Debugf("[devmapper cleanup] done")
  100. filter := "docker-" + path.Base(unitTestStoreBase)
  101. utils.Debugf("Filtering out %s\n", filter)
  102. // Unmount any leftover mounts from previous unit test runs
  103. if data, err := ioutil.ReadFile("/proc/mounts"); err != nil {
  104. return err
  105. } else {
  106. for _, line := range strings.Split(string(data), "\n") {
  107. if cols := strings.Split(line, " "); len(cols) >= 2 && strings.HasPrefix(cols[0], path.Join("/dev/mapper", filter)) {
  108. utils.Debugf("[devmapper cleanup] Unmounting device: %s", cols[1])
  109. if err := syscall.Unmount(cols[1], 0); err != nil {
  110. return fmt.Errorf("Unable to unmount %s needed to get a freash unit test environment: %s", cols[1], err)
  111. }
  112. }
  113. }
  114. }
  115. utils.Debugf("[devmapper cleanup] looking for leftover devices")
  116. // Remove any leftover devmapper devices from previous unit run tests
  117. infos, err := ioutil.ReadDir("/dev/mapper")
  118. if err != nil {
  119. // If the mapper file does not exist there is nothing to clean up
  120. if os.IsNotExist(err) {
  121. return nil
  122. }
  123. return err
  124. }
  125. pools := []string{}
  126. for _, info := range infos {
  127. if name := info.Name(); strings.HasPrefix(name, filter+"-") {
  128. if strings.HasSuffix(name, "-pool") {
  129. pools = append(pools, name)
  130. } else {
  131. if err := removeDev(name); err != nil {
  132. return err
  133. }
  134. }
  135. }
  136. }
  137. // We need to remove the pool last as the other devices block it
  138. for _, pool := range pools {
  139. utils.Debugf("[devmapper cleanup] Removing pool: %s", pool)
  140. if err := removeDev(pool); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. func init() {
  147. os.Setenv("TEST", "1")
  148. // Set unit-test specific values
  149. devmapper.DefaultDataLoopbackSize = unitTestDMDataLoopbackSize
  150. devmapper.DefaultMetaDataLoopbackSize = unitTestDMMetaDataLoopbackSize
  151. devmapper.DefaultBaseFsSize = unitTestDMBaseFsSize
  152. NetworkBridgeIface = unitTestNetworkBridge
  153. // Hack to run sys init during unit testing
  154. if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" {
  155. SysInit()
  156. return
  157. }
  158. if uid := syscall.Geteuid(); uid != 0 {
  159. log.Fatal("docker tests need to be run as root")
  160. }
  161. if err := cleanupDevMapper(); err != nil {
  162. log.Fatalf("Unable to cleanup devmapper: %s", err)
  163. }
  164. // Setup the base runtime, which will be duplicated for each test.
  165. // (no tests are run directly in the base)
  166. setupBaseImage()
  167. // Create the "global runtime" with a long-running daemon for integration tests
  168. spawnGlobalDaemon()
  169. startFds, startGoroutines = utils.GetTotalUsedFds(), runtime.NumGoroutine()
  170. }
  171. func setupBaseImage() {
  172. runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, false)
  173. if err != nil {
  174. log.Fatalf("Unable to create a runtime for tests:", err)
  175. }
  176. // Create the "Server"
  177. srv := &Server{
  178. runtime: runtime,
  179. enableCors: false,
  180. pullingPool: make(map[string]struct{}),
  181. pushingPool: make(map[string]struct{}),
  182. }
  183. // If the unit test is not found, try to download it.
  184. if img, err := runtime.repositories.LookupImage(unitTestImageName); err != nil || img.ID != unitTestImageID {
  185. // Retrieve the Image
  186. if err := srv.ImagePull(unitTestImageName, "", os.Stdout, utils.NewStreamFormatter(false), nil, nil, true); err != nil {
  187. log.Fatalf("Unable to pull the test image:", err)
  188. }
  189. }
  190. }
  191. func spawnGlobalDaemon() {
  192. if globalRuntime != nil {
  193. utils.Debugf("Global runtime already exists. Skipping.")
  194. return
  195. }
  196. globalRuntime = mkRuntime(log.New(os.Stderr, "", 0))
  197. srv := &Server{
  198. runtime: globalRuntime,
  199. enableCors: false,
  200. pullingPool: make(map[string]struct{}),
  201. pushingPool: make(map[string]struct{}),
  202. }
  203. // Spawn a Daemon
  204. go func() {
  205. utils.Debugf("Spawning global daemon for integration tests")
  206. if err := ListenAndServe(testDaemonProto, testDaemonAddr, srv, os.Getenv("DEBUG") != ""); err != nil {
  207. log.Fatalf("Unable to spawn the test daemon:", err)
  208. }
  209. }()
  210. // Give some time to ListenAndServer to actually start
  211. // FIXME: use inmem transports instead of tcp
  212. time.Sleep(time.Second)
  213. }
  214. // FIXME: test that ImagePull(json=true) send correct json output
  215. func GetTestImage(runtime *Runtime) *Image {
  216. imgs, err := runtime.graph.Map()
  217. if err != nil {
  218. log.Fatalf("Unable to get the test image:", err)
  219. }
  220. for _, image := range imgs {
  221. if image.ID == unitTestImageID {
  222. return image
  223. }
  224. }
  225. log.Fatalf("Test image %v not found", unitTestImageID)
  226. return nil
  227. }
  228. func TestRuntimeCreate(t *testing.T) {
  229. runtime := mkRuntime(t)
  230. defer nuke(runtime)
  231. // Make sure we start we 0 containers
  232. if len(runtime.List()) != 0 {
  233. t.Errorf("Expected 0 containers, %v found", len(runtime.List()))
  234. }
  235. container, err := runtime.Create(&Config{
  236. Image: GetTestImage(runtime).ID,
  237. Cmd: []string{"ls", "-al"},
  238. },
  239. )
  240. if err != nil {
  241. t.Fatal(err)
  242. }
  243. // Make sure we can find the newly created container with List()
  244. if len(runtime.List()) != 1 {
  245. t.Errorf("Expected 1 container, %v found", len(runtime.List()))
  246. }
  247. // Make sure the container List() returns is the right one
  248. if runtime.List()[0].ID != container.ID {
  249. t.Errorf("Unexpected container %v returned by List", runtime.List()[0])
  250. }
  251. // Make sure we can get the container with Get()
  252. if runtime.Get(container.ID) == nil {
  253. t.Errorf("Unable to get newly created container")
  254. }
  255. // Make sure it is the right container
  256. if runtime.Get(container.ID) != container {
  257. t.Errorf("Get() returned the wrong container")
  258. }
  259. // Make sure Exists returns it as existing
  260. if !runtime.Exists(container.ID) {
  261. t.Errorf("Exists() returned false for a newly created container")
  262. }
  263. // Make sure crete with bad parameters returns an error
  264. _, err = runtime.Create(
  265. &Config{
  266. Image: GetTestImage(runtime).ID,
  267. },
  268. )
  269. if err == nil {
  270. t.Fatal("Builder.Create should throw an error when Cmd is missing")
  271. }
  272. _, err = runtime.Create(
  273. &Config{
  274. Image: GetTestImage(runtime).ID,
  275. Cmd: []string{},
  276. },
  277. )
  278. if err == nil {
  279. t.Fatal("Builder.Create should throw an error when Cmd is empty")
  280. }
  281. }
  282. func TestDestroy(t *testing.T) {
  283. runtime := mkRuntime(t)
  284. defer nuke(runtime)
  285. container, err := runtime.Create(&Config{
  286. Image: GetTestImage(runtime).ID,
  287. Cmd: []string{"ls", "-al"},
  288. },
  289. )
  290. if err != nil {
  291. t.Fatal(err)
  292. }
  293. // Destroy
  294. if err := runtime.Destroy(container); err != nil {
  295. t.Error(err)
  296. }
  297. // Make sure runtime.Exists() behaves correctly
  298. if runtime.Exists("test_destroy") {
  299. t.Errorf("Exists() returned true")
  300. }
  301. // Make sure runtime.List() doesn't list the destroyed container
  302. if len(runtime.List()) != 0 {
  303. t.Errorf("Expected 0 container, %v found", len(runtime.List()))
  304. }
  305. // Make sure runtime.Get() refuses to return the unexisting container
  306. if runtime.Get(container.ID) != nil {
  307. t.Errorf("Unable to get newly created container")
  308. }
  309. // Make sure the container root directory does not exist anymore
  310. _, err = os.Stat(container.root)
  311. if err == nil || !os.IsNotExist(err) {
  312. t.Errorf("Container root directory still exists after destroy")
  313. }
  314. // Test double destroy
  315. if err := runtime.Destroy(container); err == nil {
  316. // It should have failed
  317. t.Errorf("Double destroy did not fail")
  318. }
  319. }
  320. func TestGet(t *testing.T) {
  321. runtime := mkRuntime(t)
  322. defer nuke(runtime)
  323. container1, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  324. defer runtime.Destroy(container1)
  325. container2, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  326. defer runtime.Destroy(container2)
  327. container3, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  328. defer runtime.Destroy(container3)
  329. if runtime.Get(container1.ID) != container1 {
  330. t.Errorf("Get(test1) returned %v while expecting %v", runtime.Get(container1.ID), container1)
  331. }
  332. if runtime.Get(container2.ID) != container2 {
  333. t.Errorf("Get(test2) returned %v while expecting %v", runtime.Get(container2.ID), container2)
  334. }
  335. if runtime.Get(container3.ID) != container3 {
  336. t.Errorf("Get(test3) returned %v while expecting %v", runtime.Get(container3.ID), container3)
  337. }
  338. }
  339. func startEchoServerContainer(t *testing.T, proto string) (*Runtime, *Container, string) {
  340. var err error
  341. runtime := mkRuntime(t)
  342. port := 5554
  343. var container *Container
  344. var strPort string
  345. for {
  346. port += 1
  347. strPort = strconv.Itoa(port)
  348. var cmd string
  349. if proto == "tcp" {
  350. cmd = "socat TCP-LISTEN:" + strPort + ",reuseaddr,fork EXEC:/bin/cat"
  351. } else if proto == "udp" {
  352. cmd = "socat UDP-RECVFROM:" + strPort + ",fork EXEC:/bin/cat"
  353. } else {
  354. t.Fatal(fmt.Errorf("Unknown protocol %v", proto))
  355. }
  356. t.Log("Trying port", strPort)
  357. container, err = runtime.Create(&Config{
  358. Image: GetTestImage(runtime).ID,
  359. Cmd: []string{"sh", "-c", cmd},
  360. PortSpecs: []string{fmt.Sprintf("%s/%s", strPort, proto)},
  361. })
  362. if container != nil {
  363. break
  364. }
  365. if err != nil {
  366. nuke(runtime)
  367. t.Fatal(err)
  368. }
  369. t.Logf("Port %v already in use", strPort)
  370. }
  371. hostConfig := &HostConfig{}
  372. if err := container.Start(hostConfig); err != nil {
  373. nuke(runtime)
  374. t.Fatal(err)
  375. }
  376. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  377. for !container.State.Running {
  378. time.Sleep(10 * time.Millisecond)
  379. }
  380. })
  381. // Even if the state is running, lets give some time to lxc to spawn the process
  382. container.WaitTimeout(500 * time.Millisecond)
  383. strPort = container.NetworkSettings.PortMapping[strings.Title(proto)][strPort]
  384. return runtime, container, strPort
  385. }
  386. // Run a container with a TCP port allocated, and test that it can receive connections on localhost
  387. func TestAllocateTCPPortLocalhost(t *testing.T) {
  388. runtime, container, port := startEchoServerContainer(t, "tcp")
  389. defer nuke(runtime)
  390. defer container.Kill()
  391. for i := 0; i != 10; i++ {
  392. conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", port))
  393. if err != nil {
  394. t.Fatal(err)
  395. }
  396. defer conn.Close()
  397. input := bytes.NewBufferString("well hello there\n")
  398. _, err = conn.Write(input.Bytes())
  399. if err != nil {
  400. t.Fatal(err)
  401. }
  402. buf := make([]byte, 16)
  403. read := 0
  404. conn.SetReadDeadline(time.Now().Add(3 * time.Second))
  405. read, err = conn.Read(buf)
  406. if err != nil {
  407. if err, ok := err.(*net.OpError); ok {
  408. if err.Err == syscall.ECONNRESET {
  409. t.Logf("Connection reset by the proxy, socat is probably not listening yet, trying again in a sec")
  410. conn.Close()
  411. time.Sleep(time.Second)
  412. continue
  413. }
  414. if err.Timeout() {
  415. t.Log("Timeout, trying again")
  416. conn.Close()
  417. continue
  418. }
  419. }
  420. t.Fatal(err)
  421. }
  422. output := string(buf[:read])
  423. if !strings.Contains(output, "well hello there") {
  424. t.Fatal(fmt.Errorf("[%v] doesn't contain [well hello there]", output))
  425. } else {
  426. return
  427. }
  428. }
  429. t.Fatal("No reply from the container")
  430. }
  431. // Run a container with an UDP port allocated, and test that it can receive connections on localhost
  432. func TestAllocateUDPPortLocalhost(t *testing.T) {
  433. runtime, container, port := startEchoServerContainer(t, "udp")
  434. defer nuke(runtime)
  435. defer container.Kill()
  436. conn, err := net.Dial("udp", fmt.Sprintf("localhost:%v", port))
  437. if err != nil {
  438. t.Fatal(err)
  439. }
  440. defer conn.Close()
  441. input := bytes.NewBufferString("well hello there\n")
  442. buf := make([]byte, 16)
  443. // Try for a minute, for some reason the select in socat may take ages
  444. // to return even though everything on the path seems fine (i.e: the
  445. // UDPProxy forwards the traffic correctly and you can see the packets
  446. // on the interface from within the container).
  447. for i := 0; i != 120; i++ {
  448. _, err := conn.Write(input.Bytes())
  449. if err != nil {
  450. t.Fatal(err)
  451. }
  452. conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
  453. read, err := conn.Read(buf)
  454. if err == nil {
  455. output := string(buf[:read])
  456. if strings.Contains(output, "well hello there") {
  457. return
  458. }
  459. }
  460. }
  461. t.Fatal("No reply from the container")
  462. }
  463. func TestRestore(t *testing.T) {
  464. runtime1 := mkRuntime(t)
  465. defer nuke(runtime1)
  466. // Create a container with one instance of docker
  467. container1, _, _ := mkContainer(runtime1, []string{"_", "ls", "-al"}, t)
  468. defer runtime1.Destroy(container1)
  469. // Create a second container meant to be killed
  470. container2, _, _ := mkContainer(runtime1, []string{"-i", "_", "/bin/cat"}, t)
  471. defer runtime1.Destroy(container2)
  472. // Start the container non blocking
  473. hostConfig := &HostConfig{}
  474. if err := container2.Start(hostConfig); err != nil {
  475. t.Fatal(err)
  476. }
  477. if !container2.State.Running {
  478. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  479. }
  480. // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running'
  481. cStdin, _ := container2.StdinPipe()
  482. cStdin.Close()
  483. if err := container2.WaitTimeout(2 * time.Second); err != nil {
  484. t.Fatal(err)
  485. }
  486. container2.State.Running = true
  487. container2.ToDisk()
  488. if len(runtime1.List()) != 2 {
  489. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  490. }
  491. if err := container1.Run(); err != nil {
  492. t.Fatal(err)
  493. }
  494. if !container2.State.Running {
  495. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  496. }
  497. // Here are are simulating a docker restart - that is, reloading all containers
  498. // from scratch
  499. runtime2, err := NewRuntimeFromDirectory(runtime1.root, false)
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. defer nuke(runtime2)
  504. if len(runtime2.List()) != 2 {
  505. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  506. }
  507. runningCount := 0
  508. for _, c := range runtime2.List() {
  509. if c.State.Running {
  510. t.Errorf("Running container found: %v (%v)", c.ID, c.Path)
  511. runningCount++
  512. }
  513. }
  514. if runningCount != 0 {
  515. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  516. }
  517. container3 := runtime2.Get(container1.ID)
  518. if container3 == nil {
  519. t.Fatal("Unable to Get container")
  520. }
  521. if err := container3.Run(); err != nil {
  522. t.Fatal(err)
  523. }
  524. container2.State.Running = false
  525. }
  526. func TestContainerCreatedWithDefaultFilesystemType(t *testing.T) {
  527. runtime := mkRuntime(t)
  528. defer nuke(runtime)
  529. container, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  530. defer runtime.Destroy(container)
  531. if container.FilesystemType != DefaultFilesystemType {
  532. t.Fatalf("Container filesystem type should be %s but got %s", DefaultFilesystemType, container.FilesystemType)
  533. }
  534. }