runtime_test.go 21 KB

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