runtime_test.go 12 KB

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