runtime_test.go 11 KB

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