runtime_test.go 10 KB

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