runtime_test.go 20 KB

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