runtime_test.go 9.5 KB

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