runtime_test.go 13 KB

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