runtime_test.go 12 KB

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