runtime_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. package docker
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/dotcloud/docker"
  6. "github.com/dotcloud/docker/engine"
  7. "github.com/dotcloud/docker/image"
  8. "github.com/dotcloud/docker/nat"
  9. "github.com/dotcloud/docker/runconfig"
  10. "github.com/dotcloud/docker/sysinit"
  11. "github.com/dotcloud/docker/utils"
  12. "io"
  13. "log"
  14. "net"
  15. "net/url"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "syscall"
  22. "testing"
  23. "time"
  24. )
  25. const (
  26. unitTestImageName = "docker-test-image"
  27. unitTestImageID = "83599e29c455eb719f77d799bc7c51521b9551972f5a850d7ad265bc1b5292f6" // 1.0
  28. unitTestImageIDShort = "83599e29c455"
  29. unitTestNetworkBridge = "testdockbr0"
  30. unitTestStoreBase = "/var/lib/docker/unit-tests"
  31. testDaemonAddr = "127.0.0.1:4270"
  32. testDaemonProto = "tcp"
  33. )
  34. var (
  35. // FIXME: globalRuntime is deprecated by globalEngine. All tests should be converted.
  36. globalRuntime *docker.Runtime
  37. globalEngine *engine.Engine
  38. startFds int
  39. startGoroutines int
  40. )
  41. // FIXME: nuke() is deprecated by Runtime.Nuke()
  42. func nuke(runtime *docker.Runtime) error {
  43. return runtime.Nuke()
  44. }
  45. // FIXME: cleanup and nuke are redundant.
  46. func cleanup(eng *engine.Engine, t *testing.T) error {
  47. runtime := mkRuntimeFromEngine(eng, t)
  48. for _, container := range runtime.List() {
  49. container.Kill()
  50. runtime.Destroy(container)
  51. }
  52. job := eng.Job("images")
  53. images, err := job.Stdout.AddTable()
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. if err := job.Run(); err != nil {
  58. t.Fatal(err)
  59. }
  60. for _, image := range images.Data {
  61. if image.Get("Id") != unitTestImageID {
  62. eng.Job("image_delete", image.Get("Id")).Run()
  63. }
  64. }
  65. return nil
  66. }
  67. func layerArchive(tarfile string) (io.Reader, error) {
  68. // FIXME: need to close f somewhere
  69. f, err := os.Open(tarfile)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return f, nil
  74. }
  75. func init() {
  76. // Always use the same driver (vfs) for all integration tests.
  77. // To test other drivers, we need a dedicated driver validation suite.
  78. os.Setenv("DOCKER_DRIVER", "vfs")
  79. os.Setenv("TEST", "1")
  80. // Hack to run sys init during unit testing
  81. if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
  82. sysinit.SysInit()
  83. return
  84. }
  85. if uid := syscall.Geteuid(); uid != 0 {
  86. log.Fatal("docker tests need to be run as root")
  87. }
  88. // Copy dockerinit into our current testing directory, if provided (so we can test a separate dockerinit binary)
  89. if dockerinit := os.Getenv("TEST_DOCKERINIT_PATH"); dockerinit != "" {
  90. src, err := os.Open(dockerinit)
  91. if err != nil {
  92. log.Fatalf("Unable to open TEST_DOCKERINIT_PATH: %s\n", err)
  93. }
  94. defer src.Close()
  95. dst, err := os.OpenFile(filepath.Join(filepath.Dir(utils.SelfPath()), "dockerinit"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0555)
  96. if err != nil {
  97. log.Fatalf("Unable to create dockerinit in test directory: %s\n", err)
  98. }
  99. defer dst.Close()
  100. if _, err := io.Copy(dst, src); err != nil {
  101. log.Fatalf("Unable to copy dockerinit to TEST_DOCKERINIT_PATH: %s\n", err)
  102. }
  103. dst.Close()
  104. src.Close()
  105. }
  106. // Setup the base runtime, which will be duplicated for each test.
  107. // (no tests are run directly in the base)
  108. setupBaseImage()
  109. // Create the "global runtime" with a long-running daemon for integration tests
  110. spawnGlobalDaemon()
  111. startFds, startGoroutines = utils.GetTotalUsedFds(), runtime.NumGoroutine()
  112. }
  113. func setupBaseImage() {
  114. eng := newTestEngine(log.New(os.Stderr, "", 0), false, unitTestStoreBase)
  115. job := eng.Job("inspect", unitTestImageName, "image")
  116. img, _ := job.Stdout.AddEnv()
  117. // If the unit test is not found, try to download it.
  118. if err := job.Run(); err != nil || img.Get("id") != unitTestImageID {
  119. // Retrieve the Image
  120. job = eng.Job("pull", unitTestImageName)
  121. job.Stdout.Add(utils.NopWriteCloser(os.Stdout))
  122. if err := job.Run(); err != nil {
  123. log.Fatalf("Unable to pull the test image: %s", err)
  124. }
  125. }
  126. }
  127. func spawnGlobalDaemon() {
  128. if globalRuntime != nil {
  129. utils.Debugf("Global runtime already exists. Skipping.")
  130. return
  131. }
  132. t := log.New(os.Stderr, "", 0)
  133. eng := NewTestEngine(t)
  134. globalEngine = eng
  135. globalRuntime = mkRuntimeFromEngine(eng, t)
  136. // Spawn a Daemon
  137. go func() {
  138. utils.Debugf("Spawning global daemon for integration tests")
  139. listenURL := &url.URL{
  140. Scheme: testDaemonProto,
  141. Host: testDaemonAddr,
  142. }
  143. job := eng.Job("serveapi", listenURL.String())
  144. job.SetenvBool("Logging", true)
  145. if err := job.Run(); err != nil {
  146. log.Fatalf("Unable to spawn the test daemon: %s", err)
  147. }
  148. }()
  149. // Give some time to ListenAndServer to actually start
  150. // FIXME: use inmem transports instead of tcp
  151. time.Sleep(time.Second)
  152. if err := eng.Job("acceptconnections").Run(); err != nil {
  153. log.Fatalf("Unable to accept connections for test api: %s", err)
  154. }
  155. }
  156. // FIXME: test that ImagePull(json=true) send correct json output
  157. func GetTestImage(runtime *docker.Runtime) *image.Image {
  158. imgs, err := runtime.Graph().Map()
  159. if err != nil {
  160. log.Fatalf("Unable to get the test image: %s", err)
  161. }
  162. for _, image := range imgs {
  163. if image.ID == unitTestImageID {
  164. return image
  165. }
  166. }
  167. log.Fatalf("Test image %v not found in %s: %s", unitTestImageID, runtime.Graph().Root, imgs)
  168. return nil
  169. }
  170. func TestRuntimeCreate(t *testing.T) {
  171. runtime := mkRuntime(t)
  172. defer nuke(runtime)
  173. // Make sure we start we 0 containers
  174. if len(runtime.List()) != 0 {
  175. t.Errorf("Expected 0 containers, %v found", len(runtime.List()))
  176. }
  177. container, _, err := runtime.Create(&runconfig.Config{
  178. Image: GetTestImage(runtime).ID,
  179. Cmd: []string{"ls", "-al"},
  180. },
  181. "",
  182. )
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. defer func() {
  187. if err := runtime.Destroy(container); err != nil {
  188. t.Error(err)
  189. }
  190. }()
  191. // Make sure we can find the newly created container with List()
  192. if len(runtime.List()) != 1 {
  193. t.Errorf("Expected 1 container, %v found", len(runtime.List()))
  194. }
  195. // Make sure the container List() returns is the right one
  196. if runtime.List()[0].ID != container.ID {
  197. t.Errorf("Unexpected container %v returned by List", runtime.List()[0])
  198. }
  199. // Make sure we can get the container with Get()
  200. if runtime.Get(container.ID) == nil {
  201. t.Errorf("Unable to get newly created container")
  202. }
  203. // Make sure it is the right container
  204. if runtime.Get(container.ID) != container {
  205. t.Errorf("Get() returned the wrong container")
  206. }
  207. // Make sure Exists returns it as existing
  208. if !runtime.Exists(container.ID) {
  209. t.Errorf("Exists() returned false for a newly created container")
  210. }
  211. // Test that conflict error displays correct details
  212. testContainer, _, _ := runtime.Create(
  213. &runconfig.Config{
  214. Image: GetTestImage(runtime).ID,
  215. Cmd: []string{"ls", "-al"},
  216. },
  217. "conflictname",
  218. )
  219. if _, _, err := runtime.Create(&runconfig.Config{Image: GetTestImage(runtime).ID, Cmd: []string{"ls", "-al"}}, testContainer.Name); err == nil || !strings.Contains(err.Error(), utils.TruncateID(testContainer.ID)) {
  220. t.Fatalf("Name conflict error doesn't include the correct short id. Message was: %s", err.Error())
  221. }
  222. // Make sure create with bad parameters returns an error
  223. if _, _, err = runtime.Create(&runconfig.Config{Image: GetTestImage(runtime).ID}, ""); err == nil {
  224. t.Fatal("Builder.Create should throw an error when Cmd is missing")
  225. }
  226. if _, _, err := runtime.Create(
  227. &runconfig.Config{
  228. Image: GetTestImage(runtime).ID,
  229. Cmd: []string{},
  230. },
  231. "",
  232. ); err == nil {
  233. t.Fatal("Builder.Create should throw an error when Cmd is empty")
  234. }
  235. config := &runconfig.Config{
  236. Image: GetTestImage(runtime).ID,
  237. Cmd: []string{"/bin/ls"},
  238. PortSpecs: []string{"80"},
  239. }
  240. container, _, err = runtime.Create(config, "")
  241. _, err = runtime.Commit(container, "testrepo", "testtag", "", "", config)
  242. if err != nil {
  243. t.Error(err)
  244. }
  245. // test expose 80:8000
  246. container, warnings, err := runtime.Create(&runconfig.Config{
  247. Image: GetTestImage(runtime).ID,
  248. Cmd: []string{"ls", "-al"},
  249. PortSpecs: []string{"80:8000"},
  250. },
  251. "",
  252. )
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. if warnings == nil || len(warnings) != 1 {
  257. t.Error("Expected a warning, got none")
  258. }
  259. }
  260. func TestDestroy(t *testing.T) {
  261. runtime := mkRuntime(t)
  262. defer nuke(runtime)
  263. container, _, err := runtime.Create(&runconfig.Config{
  264. Image: GetTestImage(runtime).ID,
  265. Cmd: []string{"ls", "-al"},
  266. }, "")
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. // Destroy
  271. if err := runtime.Destroy(container); err != nil {
  272. t.Error(err)
  273. }
  274. // Make sure runtime.Exists() behaves correctly
  275. if runtime.Exists("test_destroy") {
  276. t.Errorf("Exists() returned true")
  277. }
  278. // Make sure runtime.List() doesn't list the destroyed container
  279. if len(runtime.List()) != 0 {
  280. t.Errorf("Expected 0 container, %v found", len(runtime.List()))
  281. }
  282. // Make sure runtime.Get() refuses to return the unexisting container
  283. if runtime.Get(container.ID) != nil {
  284. t.Errorf("Unable to get newly created container")
  285. }
  286. // Test double destroy
  287. if err := runtime.Destroy(container); err == nil {
  288. // It should have failed
  289. t.Errorf("Double destroy did not fail")
  290. }
  291. }
  292. func TestGet(t *testing.T) {
  293. runtime := mkRuntime(t)
  294. defer nuke(runtime)
  295. container1, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  296. defer runtime.Destroy(container1)
  297. container2, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  298. defer runtime.Destroy(container2)
  299. container3, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  300. defer runtime.Destroy(container3)
  301. if runtime.Get(container1.ID) != container1 {
  302. t.Errorf("Get(test1) returned %v while expecting %v", runtime.Get(container1.ID), container1)
  303. }
  304. if runtime.Get(container2.ID) != container2 {
  305. t.Errorf("Get(test2) returned %v while expecting %v", runtime.Get(container2.ID), container2)
  306. }
  307. if runtime.Get(container3.ID) != container3 {
  308. t.Errorf("Get(test3) returned %v while expecting %v", runtime.Get(container3.ID), container3)
  309. }
  310. }
  311. func startEchoServerContainer(t *testing.T, proto string) (*docker.Runtime, *docker.Container, string) {
  312. var (
  313. err error
  314. id string
  315. strPort string
  316. eng = NewTestEngine(t)
  317. runtime = mkRuntimeFromEngine(eng, t)
  318. port = 5554
  319. p nat.Port
  320. )
  321. defer func() {
  322. if err != nil {
  323. runtime.Nuke()
  324. }
  325. }()
  326. for {
  327. port += 1
  328. strPort = strconv.Itoa(port)
  329. var cmd string
  330. if proto == "tcp" {
  331. cmd = "socat TCP-LISTEN:" + strPort + ",reuseaddr,fork EXEC:/bin/cat"
  332. } else if proto == "udp" {
  333. cmd = "socat UDP-RECVFROM:" + strPort + ",fork EXEC:/bin/cat"
  334. } else {
  335. t.Fatal(fmt.Errorf("Unknown protocol %v", proto))
  336. }
  337. ep := make(map[nat.Port]struct{}, 1)
  338. p = nat.Port(fmt.Sprintf("%s/%s", strPort, proto))
  339. ep[p] = struct{}{}
  340. jobCreate := eng.Job("create")
  341. jobCreate.Setenv("Image", unitTestImageID)
  342. jobCreate.SetenvList("Cmd", []string{"sh", "-c", cmd})
  343. jobCreate.SetenvList("PortSpecs", []string{fmt.Sprintf("%s/%s", strPort, proto)})
  344. jobCreate.SetenvJson("ExposedPorts", ep)
  345. jobCreate.Stdout.AddString(&id)
  346. if err := jobCreate.Run(); err != nil {
  347. t.Fatal(err)
  348. }
  349. // FIXME: this relies on the undocumented behavior of runtime.Create
  350. // which will return a nil error AND container if the exposed ports
  351. // are invalid. That behavior should be fixed!
  352. if id != "" {
  353. break
  354. }
  355. t.Logf("Port %v already in use, trying another one", strPort)
  356. }
  357. jobStart := eng.Job("start", id)
  358. portBindings := make(map[nat.Port][]nat.PortBinding)
  359. portBindings[p] = []nat.PortBinding{
  360. {},
  361. }
  362. if err := jobStart.SetenvJson("PortsBindings", portBindings); err != nil {
  363. t.Fatal(err)
  364. }
  365. if err := jobStart.Run(); err != nil {
  366. t.Fatal(err)
  367. }
  368. container := runtime.Get(id)
  369. if container == nil {
  370. t.Fatalf("Couldn't fetch test container %s", id)
  371. }
  372. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  373. for !container.State.IsRunning() {
  374. time.Sleep(10 * time.Millisecond)
  375. }
  376. })
  377. // Even if the state is running, lets give some time to lxc to spawn the process
  378. container.WaitTimeout(500 * time.Millisecond)
  379. strPort = container.NetworkSettings.Ports[p][0].HostPort
  380. return runtime, container, strPort
  381. }
  382. // Run a container with a TCP port allocated, and test that it can receive connections on localhost
  383. func TestAllocateTCPPortLocalhost(t *testing.T) {
  384. runtime, container, port := startEchoServerContainer(t, "tcp")
  385. defer nuke(runtime)
  386. defer container.Kill()
  387. for i := 0; i != 10; i++ {
  388. conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", port))
  389. if err != nil {
  390. t.Fatal(err)
  391. }
  392. defer conn.Close()
  393. input := bytes.NewBufferString("well hello there\n")
  394. _, err = conn.Write(input.Bytes())
  395. if err != nil {
  396. t.Fatal(err)
  397. }
  398. buf := make([]byte, 16)
  399. read := 0
  400. conn.SetReadDeadline(time.Now().Add(3 * time.Second))
  401. read, err = conn.Read(buf)
  402. if err != nil {
  403. if err, ok := err.(*net.OpError); ok {
  404. if err.Err == syscall.ECONNRESET {
  405. t.Logf("Connection reset by the proxy, socat is probably not listening yet, trying again in a sec")
  406. conn.Close()
  407. time.Sleep(time.Second)
  408. continue
  409. }
  410. if err.Timeout() {
  411. t.Log("Timeout, trying again")
  412. conn.Close()
  413. continue
  414. }
  415. }
  416. t.Fatal(err)
  417. }
  418. output := string(buf[:read])
  419. if !strings.Contains(output, "well hello there") {
  420. t.Fatal(fmt.Errorf("[%v] doesn't contain [well hello there]", output))
  421. } else {
  422. return
  423. }
  424. }
  425. t.Fatal("No reply from the container")
  426. }
  427. // Run a container with an UDP port allocated, and test that it can receive connections on localhost
  428. func TestAllocateUDPPortLocalhost(t *testing.T) {
  429. runtime, container, port := startEchoServerContainer(t, "udp")
  430. defer nuke(runtime)
  431. defer container.Kill()
  432. conn, err := net.Dial("udp", fmt.Sprintf("localhost:%v", port))
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. defer conn.Close()
  437. input := bytes.NewBufferString("well hello there\n")
  438. buf := make([]byte, 16)
  439. // Try for a minute, for some reason the select in socat may take ages
  440. // to return even though everything on the path seems fine (i.e: the
  441. // UDPProxy forwards the traffic correctly and you can see the packets
  442. // on the interface from within the container).
  443. for i := 0; i != 120; i++ {
  444. _, err := conn.Write(input.Bytes())
  445. if err != nil {
  446. t.Fatal(err)
  447. }
  448. conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
  449. read, err := conn.Read(buf)
  450. if err == nil {
  451. output := string(buf[:read])
  452. if strings.Contains(output, "well hello there") {
  453. return
  454. }
  455. }
  456. }
  457. t.Fatal("No reply from the container")
  458. }
  459. func TestRestore(t *testing.T) {
  460. eng := NewTestEngine(t)
  461. runtime1 := mkRuntimeFromEngine(eng, t)
  462. defer runtime1.Nuke()
  463. // Create a container with one instance of docker
  464. container1, _, _ := mkContainer(runtime1, []string{"_", "ls", "-al"}, t)
  465. defer runtime1.Destroy(container1)
  466. // Create a second container meant to be killed
  467. container2, _, _ := mkContainer(runtime1, []string{"-i", "_", "/bin/cat"}, t)
  468. defer runtime1.Destroy(container2)
  469. // Start the container non blocking
  470. if err := container2.Start(); err != nil {
  471. t.Fatal(err)
  472. }
  473. if !container2.State.IsRunning() {
  474. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  475. }
  476. // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running'
  477. cStdin, _ := container2.StdinPipe()
  478. cStdin.Close()
  479. if err := container2.WaitTimeout(2 * time.Second); err != nil {
  480. t.Fatal(err)
  481. }
  482. container2.State.SetRunning(42)
  483. container2.ToDisk()
  484. if len(runtime1.List()) != 2 {
  485. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  486. }
  487. if err := container1.Run(); err != nil {
  488. t.Fatal(err)
  489. }
  490. if !container2.State.IsRunning() {
  491. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  492. }
  493. // Here are are simulating a docker restart - that is, reloading all containers
  494. // from scratch
  495. eng = newTestEngine(t, false, eng.Root())
  496. runtime2 := mkRuntimeFromEngine(eng, t)
  497. if len(runtime2.List()) != 2 {
  498. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  499. }
  500. runningCount := 0
  501. for _, c := range runtime2.List() {
  502. if c.State.IsRunning() {
  503. t.Errorf("Running container found: %v (%v)", c.ID, c.Path)
  504. runningCount++
  505. }
  506. }
  507. if runningCount != 0 {
  508. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  509. }
  510. container3 := runtime2.Get(container1.ID)
  511. if container3 == nil {
  512. t.Fatal("Unable to Get container")
  513. }
  514. if err := container3.Run(); err != nil {
  515. t.Fatal(err)
  516. }
  517. container2.State.SetStopped(0)
  518. }
  519. func TestDefaultContainerName(t *testing.T) {
  520. eng := NewTestEngine(t)
  521. runtime := mkRuntimeFromEngine(eng, t)
  522. defer nuke(runtime)
  523. config, _, _, err := runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
  524. if err != nil {
  525. t.Fatal(err)
  526. }
  527. container := runtime.Get(createNamedTestContainer(eng, config, t, "some_name"))
  528. containerID := container.ID
  529. if container.Name != "/some_name" {
  530. t.Fatalf("Expect /some_name got %s", container.Name)
  531. }
  532. if c := runtime.Get("/some_name"); c == nil {
  533. t.Fatalf("Couldn't retrieve test container as /some_name")
  534. } else if c.ID != containerID {
  535. t.Fatalf("Container /some_name has ID %s instead of %s", c.ID, containerID)
  536. }
  537. }
  538. func TestRandomContainerName(t *testing.T) {
  539. eng := NewTestEngine(t)
  540. runtime := mkRuntimeFromEngine(eng, t)
  541. defer nuke(runtime)
  542. config, _, _, err := runconfig.Parse([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  543. if err != nil {
  544. t.Fatal(err)
  545. }
  546. container := runtime.Get(createTestContainer(eng, config, t))
  547. containerID := container.ID
  548. if container.Name == "" {
  549. t.Fatalf("Expected not empty container name")
  550. }
  551. if c := runtime.Get(container.Name); c == nil {
  552. log.Fatalf("Could not lookup container %s by its name", container.Name)
  553. } else if c.ID != containerID {
  554. log.Fatalf("Looking up container name %s returned id %s instead of %s", container.Name, c.ID, containerID)
  555. }
  556. }
  557. func TestContainerNameValidation(t *testing.T) {
  558. eng := NewTestEngine(t)
  559. runtime := mkRuntimeFromEngine(eng, t)
  560. defer nuke(runtime)
  561. for _, test := range []struct {
  562. Name string
  563. Valid bool
  564. }{
  565. {"abc-123_AAA.1", true},
  566. {"\000asdf", false},
  567. } {
  568. config, _, _, err := runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
  569. if err != nil {
  570. if !test.Valid {
  571. continue
  572. }
  573. t.Fatal(err)
  574. }
  575. var shortID string
  576. job := eng.Job("create", test.Name)
  577. if err := job.ImportEnv(config); err != nil {
  578. t.Fatal(err)
  579. }
  580. job.Stdout.AddString(&shortID)
  581. if err := job.Run(); err != nil {
  582. if !test.Valid {
  583. continue
  584. }
  585. t.Fatal(err)
  586. }
  587. container := runtime.Get(shortID)
  588. if container.Name != "/"+test.Name {
  589. t.Fatalf("Expect /%s got %s", test.Name, container.Name)
  590. }
  591. if c := runtime.Get("/" + test.Name); c == nil {
  592. t.Fatalf("Couldn't retrieve test container as /%s", test.Name)
  593. } else if c.ID != container.ID {
  594. t.Fatalf("Container /%s has ID %s instead of %s", test.Name, c.ID, container.ID)
  595. }
  596. }
  597. }
  598. func TestLinkChildContainer(t *testing.T) {
  599. eng := NewTestEngine(t)
  600. runtime := mkRuntimeFromEngine(eng, t)
  601. defer nuke(runtime)
  602. config, _, _, err := runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. container := runtime.Get(createNamedTestContainer(eng, config, t, "/webapp"))
  607. webapp, err := runtime.GetByName("/webapp")
  608. if err != nil {
  609. t.Fatal(err)
  610. }
  611. if webapp.ID != container.ID {
  612. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  613. }
  614. config, _, _, err = runconfig.Parse([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. childContainer := runtime.Get(createTestContainer(eng, config, t))
  619. if err := runtime.RegisterLink(webapp, childContainer, "db"); err != nil {
  620. t.Fatal(err)
  621. }
  622. // Get the child by it's new name
  623. db, err := runtime.GetByName("/webapp/db")
  624. if err != nil {
  625. t.Fatal(err)
  626. }
  627. if db.ID != childContainer.ID {
  628. t.Fatalf("Expect db id to match container id: %s != %s", db.ID, childContainer.ID)
  629. }
  630. }
  631. func TestGetAllChildren(t *testing.T) {
  632. eng := NewTestEngine(t)
  633. runtime := mkRuntimeFromEngine(eng, t)
  634. defer nuke(runtime)
  635. config, _, _, err := runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
  636. if err != nil {
  637. t.Fatal(err)
  638. }
  639. container := runtime.Get(createNamedTestContainer(eng, config, t, "/webapp"))
  640. webapp, err := runtime.GetByName("/webapp")
  641. if err != nil {
  642. t.Fatal(err)
  643. }
  644. if webapp.ID != container.ID {
  645. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  646. }
  647. config, _, _, err = runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
  648. if err != nil {
  649. t.Fatal(err)
  650. }
  651. childContainer := runtime.Get(createTestContainer(eng, config, t))
  652. if err := runtime.RegisterLink(webapp, childContainer, "db"); err != nil {
  653. t.Fatal(err)
  654. }
  655. children, err := runtime.Children("/webapp")
  656. if err != nil {
  657. t.Fatal(err)
  658. }
  659. if children == nil {
  660. t.Fatal("Children should not be nil")
  661. }
  662. if len(children) == 0 {
  663. t.Fatal("Children should not be empty")
  664. }
  665. for key, value := range children {
  666. if key != "/webapp/db" {
  667. t.Fatalf("Expected /webapp/db got %s", key)
  668. }
  669. if value.ID != childContainer.ID {
  670. t.Fatalf("Expected id %s got %s", childContainer.ID, value.ID)
  671. }
  672. }
  673. }
  674. func TestDestroyWithInitLayer(t *testing.T) {
  675. runtime := mkRuntime(t)
  676. defer nuke(runtime)
  677. container, _, err := runtime.Create(&runconfig.Config{
  678. Image: GetTestImage(runtime).ID,
  679. Cmd: []string{"ls", "-al"},
  680. }, "")
  681. if err != nil {
  682. t.Fatal(err)
  683. }
  684. // Destroy
  685. if err := runtime.Destroy(container); err != nil {
  686. t.Fatal(err)
  687. }
  688. // Make sure runtime.Exists() behaves correctly
  689. if runtime.Exists("test_destroy") {
  690. t.Fatalf("Exists() returned true")
  691. }
  692. // Make sure runtime.List() doesn't list the destroyed container
  693. if len(runtime.List()) != 0 {
  694. t.Fatalf("Expected 0 container, %v found", len(runtime.List()))
  695. }
  696. driver := runtime.Graph().Driver()
  697. // Make sure that the container does not exist in the driver
  698. if _, err := driver.Get(container.ID); err == nil {
  699. t.Fatal("Conttainer should not exist in the driver")
  700. }
  701. // Make sure that the init layer is removed from the driver
  702. if _, err := driver.Get(fmt.Sprintf("%s-init", container.ID)); err == nil {
  703. t.Fatal("Container's init layer should not exist in the driver")
  704. }
  705. }