runtime_test.go 12 KB

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