runtime_test.go 10 KB

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