runtime_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/registry"
  5. "github.com/dotcloud/docker/utils"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "os/exec"
  11. "os/user"
  12. "sync"
  13. "testing"
  14. "time"
  15. )
  16. const unitTestImageName string = "docker-ut"
  17. const unitTestStoreBase string = "/var/lib/docker/unit-tests"
  18. func nuke(runtime *Runtime) error {
  19. var wg sync.WaitGroup
  20. for _, container := range runtime.List() {
  21. wg.Add(1)
  22. go func(c *Container) {
  23. c.Kill()
  24. wg.Done()
  25. }(container)
  26. }
  27. wg.Wait()
  28. return os.RemoveAll(runtime.root)
  29. }
  30. func CopyDirectory(source, dest string) error {
  31. if _, err := exec.Command("cp", "-ra", source, dest).Output(); err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. func layerArchive(tarfile string) (io.Reader, error) {
  37. // FIXME: need to close f somewhere
  38. f, err := os.Open(tarfile)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return f, nil
  43. }
  44. func init() {
  45. // Hack to run sys init during unit testing
  46. if utils.SelfPath() == "/sbin/init" {
  47. SysInit()
  48. return
  49. }
  50. if usr, err := user.Current(); err != nil {
  51. panic(err)
  52. } else if usr.Uid != "0" {
  53. panic("docker tests needs to be run as root")
  54. }
  55. NetworkBridgeIface = "testdockbr0"
  56. // Make it our Store root
  57. runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, false)
  58. if err != nil {
  59. panic(err)
  60. }
  61. // Create the "Server"
  62. srv := &Server{
  63. runtime: runtime,
  64. registry: registry.NewRegistry(runtime.root),
  65. }
  66. // Retrieve the Image
  67. if err := srv.ImagePull(unitTestImageName, "", "", os.Stdout); err != nil {
  68. panic(err)
  69. }
  70. }
  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 := 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. // Run a container with a TCP port allocated, and test that it can receive connections on localhost
  247. func TestAllocatePortLocalhost(t *testing.T) {
  248. runtime, err := newTestRuntime()
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. container, err := NewBuilder(runtime).Create(&Config{
  253. Image: GetTestImage(runtime).Id,
  254. Cmd: []string{"sh", "-c", "echo well hello there | nc -l -p 5555"},
  255. PortSpecs: []string{"5555"},
  256. },
  257. )
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. if err := container.Start(); err != nil {
  262. t.Fatal(err)
  263. }
  264. defer container.Kill()
  265. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  266. for {
  267. if container.State.Running {
  268. break
  269. }
  270. time.Sleep(10 * time.Millisecond)
  271. }
  272. })
  273. conn, err := net.Dial("tcp",
  274. fmt.Sprintf(
  275. "localhost:%s", container.NetworkSettings.PortMapping["5555"],
  276. ),
  277. )
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. defer conn.Close()
  282. output, err := ioutil.ReadAll(conn)
  283. if err != nil {
  284. t.Fatal(err)
  285. }
  286. if string(output) != "well hello there\n" {
  287. t.Fatalf("Received wrong output from network connection: should be '%s', not '%s'",
  288. "well hello there\n",
  289. string(output),
  290. )
  291. }
  292. container.Wait()
  293. }
  294. func TestRestore(t *testing.T) {
  295. root, err := ioutil.TempDir("", "docker-test")
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. if err := os.Remove(root); err != nil {
  300. t.Fatal(err)
  301. }
  302. if err := CopyDirectory(unitTestStoreBase, root); err != nil {
  303. t.Fatal(err)
  304. }
  305. runtime1, err := NewRuntimeFromDirectory(root, false)
  306. if err != nil {
  307. t.Fatal(err)
  308. }
  309. builder := NewBuilder(runtime1)
  310. // Create a container with one instance of docker
  311. container1, err := builder.Create(&Config{
  312. Image: GetTestImage(runtime1).Id,
  313. Cmd: []string{"ls", "-al"},
  314. },
  315. )
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. defer runtime1.Destroy(container1)
  320. // Create a second container meant to be killed
  321. container2, err := builder.Create(&Config{
  322. Image: GetTestImage(runtime1).Id,
  323. Cmd: []string{"/bin/cat"},
  324. OpenStdin: true,
  325. },
  326. )
  327. if err != nil {
  328. t.Fatal(err)
  329. }
  330. defer runtime1.Destroy(container2)
  331. // Start the container non blocking
  332. if err := container2.Start(); err != nil {
  333. t.Fatal(err)
  334. }
  335. if !container2.State.Running {
  336. t.Fatalf("Container %v should appear as running but isn't", container2.Id)
  337. }
  338. // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running'
  339. cStdin, _ := container2.StdinPipe()
  340. cStdin.Close()
  341. if err := container2.WaitTimeout(2 * time.Second); err != nil {
  342. t.Fatal(err)
  343. }
  344. container2.State.Running = true
  345. container2.ToDisk()
  346. if len(runtime1.List()) != 2 {
  347. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  348. }
  349. if err := container1.Run(); err != nil {
  350. t.Fatal(err)
  351. }
  352. if !container2.State.Running {
  353. t.Fatalf("Container %v should appear as running but isn't", container2.Id)
  354. }
  355. // Here are are simulating a docker restart - that is, reloading all containers
  356. // from scratch
  357. runtime2, err := NewRuntimeFromDirectory(root, false)
  358. if err != nil {
  359. t.Fatal(err)
  360. }
  361. defer nuke(runtime2)
  362. if len(runtime2.List()) != 2 {
  363. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  364. }
  365. runningCount := 0
  366. for _, c := range runtime2.List() {
  367. if c.State.Running {
  368. t.Errorf("Running container found: %v (%v)", c.Id, c.Path)
  369. runningCount++
  370. }
  371. }
  372. if runningCount != 0 {
  373. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  374. }
  375. container3 := runtime2.Get(container1.Id)
  376. if container3 == nil {
  377. t.Fatal("Unable to Get container")
  378. }
  379. if err := container3.Run(); err != nil {
  380. t.Fatal(err)
  381. }
  382. container2.State.Running = false
  383. }