runtime_test.go 14 KB

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