runtime_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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.GraphPath, "linkgraph.db"))
  45. return os.RemoveAll(runtime.config.GraphPath)
  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. GraphPath: 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. )
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. defer func() {
  183. if err := runtime.Destroy(container); err != nil {
  184. t.Error(err)
  185. }
  186. }()
  187. // Make sure we can find the newly created container with List()
  188. if len(runtime.List()) != 1 {
  189. t.Errorf("Expected 1 container, %v found", len(runtime.List()))
  190. }
  191. // Make sure the container List() returns is the right one
  192. if runtime.List()[0].ID != container.ID {
  193. t.Errorf("Unexpected container %v returned by List", runtime.List()[0])
  194. }
  195. // Make sure we can get the container with Get()
  196. if runtime.Get(container.ID) == nil {
  197. t.Errorf("Unable to get newly created container")
  198. }
  199. // Make sure it is the right container
  200. if runtime.Get(container.ID) != container {
  201. t.Errorf("Get() returned the wrong container")
  202. }
  203. // Make sure Exists returns it as existing
  204. if !runtime.Exists(container.ID) {
  205. t.Errorf("Exists() returned false for a newly created container")
  206. }
  207. // Make sure create with bad parameters returns an error
  208. if _, _, err = runtime.Create(&Config{Image: GetTestImage(runtime).ID}, ""); err == nil {
  209. t.Fatal("Builder.Create should throw an error when Cmd is missing")
  210. }
  211. if _, _, err := runtime.Create(
  212. &Config{
  213. Image: GetTestImage(runtime).ID,
  214. Cmd: []string{},
  215. },
  216. "",
  217. ); err == nil {
  218. t.Fatal("Builder.Create should throw an error when Cmd is empty")
  219. }
  220. config := &Config{
  221. Image: GetTestImage(runtime).ID,
  222. Cmd: []string{"/bin/ls"},
  223. PortSpecs: []string{"80"},
  224. }
  225. container, _, err = runtime.Create(config, "")
  226. _, err = runtime.Commit(container, "testrepo", "testtag", "", "", config)
  227. if err != nil {
  228. t.Error(err)
  229. }
  230. // test expose 80:8000
  231. container, warnings, err := runtime.Create(&Config{
  232. Image: GetTestImage(runtime).ID,
  233. Cmd: []string{"ls", "-al"},
  234. PortSpecs: []string{"80:8000"},
  235. },
  236. "",
  237. )
  238. if err != nil {
  239. t.Fatal(err)
  240. }
  241. if warnings == nil {
  242. t.Error("Expected a warning, got none")
  243. }
  244. }
  245. func TestDestroy(t *testing.T) {
  246. runtime := mkRuntime(t)
  247. defer nuke(runtime)
  248. container, _, err := runtime.Create(&Config{
  249. Image: GetTestImage(runtime).ID,
  250. Cmd: []string{"ls", "-al"},
  251. }, "")
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. // Destroy
  256. if err := runtime.Destroy(container); err != nil {
  257. t.Error(err)
  258. }
  259. // Make sure runtime.Exists() behaves correctly
  260. if runtime.Exists("test_destroy") {
  261. t.Errorf("Exists() returned true")
  262. }
  263. // Make sure runtime.List() doesn't list the destroyed container
  264. if len(runtime.List()) != 0 {
  265. t.Errorf("Expected 0 container, %v found", len(runtime.List()))
  266. }
  267. // Make sure runtime.Get() refuses to return the unexisting container
  268. if runtime.Get(container.ID) != nil {
  269. t.Errorf("Unable to get newly created container")
  270. }
  271. // Make sure the container root directory does not exist anymore
  272. _, err = os.Stat(container.root)
  273. if err == nil || !os.IsNotExist(err) {
  274. t.Errorf("Container root directory still exists after destroy")
  275. }
  276. // Test double destroy
  277. if err := runtime.Destroy(container); err == nil {
  278. // It should have failed
  279. t.Errorf("Double destroy did not fail")
  280. }
  281. }
  282. func TestGet(t *testing.T) {
  283. runtime := mkRuntime(t)
  284. defer nuke(runtime)
  285. container1, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  286. defer runtime.Destroy(container1)
  287. container2, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  288. defer runtime.Destroy(container2)
  289. container3, _, _ := mkContainer(runtime, []string{"_", "ls", "-al"}, t)
  290. defer runtime.Destroy(container3)
  291. if runtime.Get(container1.ID) != container1 {
  292. t.Errorf("Get(test1) returned %v while expecting %v", runtime.Get(container1.ID), container1)
  293. }
  294. if runtime.Get(container2.ID) != container2 {
  295. t.Errorf("Get(test2) returned %v while expecting %v", runtime.Get(container2.ID), container2)
  296. }
  297. if runtime.Get(container3.ID) != container3 {
  298. t.Errorf("Get(test3) returned %v while expecting %v", runtime.Get(container3.ID), container3)
  299. }
  300. }
  301. func startEchoServerContainer(t *testing.T, proto string) (*Runtime, *Container, string) {
  302. var (
  303. err error
  304. container *Container
  305. strPort string
  306. runtime = mkRuntime(t)
  307. port = 5554
  308. p Port
  309. )
  310. for {
  311. port += 1
  312. strPort = strconv.Itoa(port)
  313. var cmd string
  314. if proto == "tcp" {
  315. cmd = "socat TCP-LISTEN:" + strPort + ",reuseaddr,fork EXEC:/bin/cat"
  316. } else if proto == "udp" {
  317. cmd = "socat UDP-RECVFROM:" + strPort + ",fork EXEC:/bin/cat"
  318. } else {
  319. t.Fatal(fmt.Errorf("Unknown protocol %v", proto))
  320. }
  321. ep := make(map[Port]struct{}, 1)
  322. p = Port(fmt.Sprintf("%s/%s", strPort, proto))
  323. ep[p] = struct{}{}
  324. container, _, err = runtime.Create(&Config{
  325. Image: GetTestImage(runtime).ID,
  326. Cmd: []string{"sh", "-c", cmd},
  327. PortSpecs: []string{fmt.Sprintf("%s/%s", strPort, proto)},
  328. ExposedPorts: ep,
  329. }, "")
  330. if err != nil {
  331. nuke(runtime)
  332. t.Fatal(err)
  333. }
  334. if container != nil {
  335. break
  336. }
  337. t.Logf("Port %v already in use, trying another one", strPort)
  338. }
  339. hostConfig := &HostConfig{
  340. PortBindings: make(map[Port][]PortBinding),
  341. }
  342. hostConfig.PortBindings[p] = []PortBinding{
  343. {},
  344. }
  345. if err := container.Start(hostConfig); err != nil {
  346. nuke(runtime)
  347. t.Fatal(err)
  348. }
  349. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  350. for !container.State.Running {
  351. time.Sleep(10 * time.Millisecond)
  352. }
  353. })
  354. // Even if the state is running, lets give some time to lxc to spawn the process
  355. container.WaitTimeout(500 * time.Millisecond)
  356. strPort = container.NetworkSettings.Ports[p][0].HostPort
  357. return runtime, container, strPort
  358. }
  359. // Run a container with a TCP port allocated, and test that it can receive connections on localhost
  360. func TestAllocateTCPPortLocalhost(t *testing.T) {
  361. runtime, container, port := startEchoServerContainer(t, "tcp")
  362. defer nuke(runtime)
  363. defer container.Kill()
  364. for i := 0; i != 10; i++ {
  365. conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", port))
  366. if err != nil {
  367. t.Fatal(err)
  368. }
  369. defer conn.Close()
  370. input := bytes.NewBufferString("well hello there\n")
  371. _, err = conn.Write(input.Bytes())
  372. if err != nil {
  373. t.Fatal(err)
  374. }
  375. buf := make([]byte, 16)
  376. read := 0
  377. conn.SetReadDeadline(time.Now().Add(3 * time.Second))
  378. read, err = conn.Read(buf)
  379. if err != nil {
  380. if err, ok := err.(*net.OpError); ok {
  381. if err.Err == syscall.ECONNRESET {
  382. t.Logf("Connection reset by the proxy, socat is probably not listening yet, trying again in a sec")
  383. conn.Close()
  384. time.Sleep(time.Second)
  385. continue
  386. }
  387. if err.Timeout() {
  388. t.Log("Timeout, trying again")
  389. conn.Close()
  390. continue
  391. }
  392. }
  393. t.Fatal(err)
  394. }
  395. output := string(buf[:read])
  396. if !strings.Contains(output, "well hello there") {
  397. t.Fatal(fmt.Errorf("[%v] doesn't contain [well hello there]", output))
  398. } else {
  399. return
  400. }
  401. }
  402. t.Fatal("No reply from the container")
  403. }
  404. // Run a container with an UDP port allocated, and test that it can receive connections on localhost
  405. func TestAllocateUDPPortLocalhost(t *testing.T) {
  406. runtime, container, port := startEchoServerContainer(t, "udp")
  407. defer nuke(runtime)
  408. defer container.Kill()
  409. conn, err := net.Dial("udp", fmt.Sprintf("localhost:%v", port))
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. defer conn.Close()
  414. input := bytes.NewBufferString("well hello there\n")
  415. buf := make([]byte, 16)
  416. // Try for a minute, for some reason the select in socat may take ages
  417. // to return even though everything on the path seems fine (i.e: the
  418. // UDPProxy forwards the traffic correctly and you can see the packets
  419. // on the interface from within the container).
  420. for i := 0; i != 120; i++ {
  421. _, err := conn.Write(input.Bytes())
  422. if err != nil {
  423. t.Fatal(err)
  424. }
  425. conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
  426. read, err := conn.Read(buf)
  427. if err == nil {
  428. output := string(buf[:read])
  429. if strings.Contains(output, "well hello there") {
  430. return
  431. }
  432. }
  433. }
  434. t.Fatal("No reply from the container")
  435. }
  436. func TestRestore(t *testing.T) {
  437. runtime1 := mkRuntime(t)
  438. defer nuke(runtime1)
  439. // Create a container with one instance of docker
  440. container1, _, _ := mkContainer(runtime1, []string{"_", "ls", "-al"}, t)
  441. defer runtime1.Destroy(container1)
  442. // Create a second container meant to be killed
  443. container2, _, _ := mkContainer(runtime1, []string{"-i", "_", "/bin/cat"}, t)
  444. defer runtime1.Destroy(container2)
  445. // Start the container non blocking
  446. hostConfig := &HostConfig{}
  447. if err := container2.Start(hostConfig); err != nil {
  448. t.Fatal(err)
  449. }
  450. if !container2.State.Running {
  451. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  452. }
  453. // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running'
  454. cStdin, _ := container2.StdinPipe()
  455. cStdin.Close()
  456. if err := container2.WaitTimeout(2 * time.Second); err != nil {
  457. t.Fatal(err)
  458. }
  459. container2.State.Running = true
  460. container2.ToDisk()
  461. if len(runtime1.List()) != 2 {
  462. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  463. }
  464. if err := container1.Run(); err != nil {
  465. t.Fatal(err)
  466. }
  467. if !container2.State.Running {
  468. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  469. }
  470. // Here are are simulating a docker restart - that is, reloading all containers
  471. // from scratch
  472. runtime1.config.AutoRestart = false
  473. runtime2, err := NewRuntimeFromDirectory(runtime1.config)
  474. if err != nil {
  475. t.Fatal(err)
  476. }
  477. defer nuke(runtime2)
  478. if len(runtime2.List()) != 2 {
  479. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  480. }
  481. runningCount := 0
  482. for _, c := range runtime2.List() {
  483. if c.State.Running {
  484. t.Errorf("Running container found: %v (%v)", c.ID, c.Path)
  485. runningCount++
  486. }
  487. }
  488. if runningCount != 0 {
  489. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  490. }
  491. container3 := runtime2.Get(container1.ID)
  492. if container3 == nil {
  493. t.Fatal("Unable to Get container")
  494. }
  495. if err := container3.Run(); err != nil {
  496. t.Fatal(err)
  497. }
  498. container2.State.Running = false
  499. }
  500. func TestReloadContainerLinks(t *testing.T) {
  501. runtime1 := mkRuntime(t)
  502. defer nuke(runtime1)
  503. // Create a container with one instance of docker
  504. container1, _, _ := mkContainer(runtime1, []string{"-i", "_", "/bin/sh"}, t)
  505. defer runtime1.Destroy(container1)
  506. // Create a second container meant to be killed
  507. container2, _, _ := mkContainer(runtime1, []string{"-i", "_", "/bin/cat"}, t)
  508. defer runtime1.Destroy(container2)
  509. // Start the container non blocking
  510. hostConfig := &HostConfig{}
  511. if err := container2.Start(hostConfig); err != nil {
  512. t.Fatal(err)
  513. }
  514. h1 := &HostConfig{}
  515. // Add a link to container 2
  516. h1.Links = []string{"/" + container2.ID + ":first"}
  517. if err := runtime1.RegisterLink(container1, container2, "first"); err != nil {
  518. t.Fatal(err)
  519. }
  520. if err := container1.Start(h1); err != nil {
  521. t.Fatal(err)
  522. }
  523. if !container2.State.Running {
  524. t.Fatalf("Container %v should appear as running but isn't", container2.ID)
  525. }
  526. if !container1.State.Running {
  527. t.Fatalf("Container %s should appear as running but isn't", container1.ID)
  528. }
  529. if len(runtime1.List()) != 2 {
  530. t.Errorf("Expected 2 container, %v found", len(runtime1.List()))
  531. }
  532. // Here are are simulating a docker restart - that is, reloading all containers
  533. // from scratch
  534. runtime1.config.AutoRestart = true
  535. runtime2, err := NewRuntimeFromDirectory(runtime1.config)
  536. if err != nil {
  537. t.Fatal(err)
  538. }
  539. defer nuke(runtime2)
  540. if len(runtime2.List()) != 2 {
  541. t.Errorf("Expected 2 container, %v found", len(runtime2.List()))
  542. }
  543. runningCount := 0
  544. for _, c := range runtime2.List() {
  545. if c.State.Running {
  546. t.Logf("Running container found: %v (%v)", c.ID, c.Path)
  547. runningCount++
  548. }
  549. }
  550. if runningCount != 2 {
  551. t.Fatalf("Expected 2 container alive, %d found", runningCount)
  552. }
  553. // Make sure container 2 ( the child of container 1 ) was registered and started first
  554. // with the runtime
  555. first := runtime2.containers.Front()
  556. if first.Value.(*Container).ID != container2.ID {
  557. t.Fatalf("Container 2 %s should be registered first in the runtime", container2.ID)
  558. }
  559. t.Logf("Number of links: %d", runtime2.containerGraph.Refs("0"))
  560. // Verify that the link is still registered in the runtime
  561. entity := runtime2.containerGraph.Get(container1.Name)
  562. if entity == nil {
  563. t.Fatal("Entity should not be nil")
  564. }
  565. }
  566. func TestDefaultContainerName(t *testing.T) {
  567. runtime := mkRuntime(t)
  568. defer nuke(runtime)
  569. srv := &Server{runtime: runtime}
  570. config, _, _, err := ParseRun([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  571. if err != nil {
  572. t.Fatal(err)
  573. }
  574. shortId, _, err := srv.ContainerCreate(config, "some_name")
  575. if err != nil {
  576. t.Fatal(err)
  577. }
  578. container := runtime.Get(shortId)
  579. containerID := container.ID
  580. if container.Name != "/some_name" {
  581. t.Fatalf("Expect /some_name got %s", container.Name)
  582. }
  583. paths := runtime.containerGraph.RefPaths(containerID)
  584. if paths == nil || len(paths) == 0 {
  585. t.Fatalf("Could not find edges for %s", containerID)
  586. }
  587. edge := paths[0]
  588. if edge.ParentID != "0" {
  589. t.Fatalf("Expected engine got %s", edge.ParentID)
  590. }
  591. if edge.EntityID != containerID {
  592. t.Fatalf("Expected %s got %s", containerID, edge.EntityID)
  593. }
  594. if edge.Name != "some_name" {
  595. t.Fatalf("Expected some_name got %s", edge.Name)
  596. }
  597. }
  598. func TestRandomContainerName(t *testing.T) {
  599. runtime := mkRuntime(t)
  600. defer nuke(runtime)
  601. srv := &Server{runtime: runtime}
  602. config, _, _, err := ParseRun([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. shortId, _, err := srv.ContainerCreate(config, "")
  607. if err != nil {
  608. t.Fatal(err)
  609. }
  610. container := runtime.Get(shortId)
  611. containerID := container.ID
  612. if container.Name == "" {
  613. t.Fatalf("Expected not empty container name")
  614. }
  615. paths := runtime.containerGraph.RefPaths(containerID)
  616. if paths == nil || len(paths) == 0 {
  617. t.Fatalf("Could not find edges for %s", containerID)
  618. }
  619. edge := paths[0]
  620. if edge.ParentID != "0" {
  621. t.Fatalf("Expected engine got %s", edge.ParentID)
  622. }
  623. if edge.EntityID != containerID {
  624. t.Fatalf("Expected %s got %s", containerID, edge.EntityID)
  625. }
  626. if edge.Name == "" {
  627. t.Fatalf("Expected not empty container name")
  628. }
  629. }
  630. func TestLinkChildContainer(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, "/webapp")
  639. if err != nil {
  640. t.Fatal(err)
  641. }
  642. container := runtime.Get(shortId)
  643. webapp, err := runtime.GetByName("/webapp")
  644. if err != nil {
  645. t.Fatal(err)
  646. }
  647. if webapp.ID != container.ID {
  648. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  649. }
  650. config, _, _, err = ParseRun([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  651. if err != nil {
  652. t.Fatal(err)
  653. }
  654. shortId, _, err = srv.ContainerCreate(config, "")
  655. if err != nil {
  656. t.Fatal(err)
  657. }
  658. childContainer := runtime.Get(shortId)
  659. if err := runtime.RegisterLink(webapp, childContainer, "db"); err != nil {
  660. t.Fatal(err)
  661. }
  662. // Get the child by it's new name
  663. db, err := runtime.GetByName("/webapp/db")
  664. if err != nil {
  665. t.Fatal(err)
  666. }
  667. if db.ID != childContainer.ID {
  668. t.Fatalf("Expect db id to match container id: %s != %s", db.ID, childContainer.ID)
  669. }
  670. }
  671. func TestGetAllChildren(t *testing.T) {
  672. runtime := mkRuntime(t)
  673. defer nuke(runtime)
  674. srv := &Server{runtime: runtime}
  675. config, _, _, err := ParseRun([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  676. if err != nil {
  677. t.Fatal(err)
  678. }
  679. shortId, _, err := srv.ContainerCreate(config, "/webapp")
  680. if err != nil {
  681. t.Fatal(err)
  682. }
  683. container := runtime.Get(shortId)
  684. webapp, err := runtime.GetByName("/webapp")
  685. if err != nil {
  686. t.Fatal(err)
  687. }
  688. if webapp.ID != container.ID {
  689. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  690. }
  691. config, _, _, err = ParseRun([]string{GetTestImage(runtime).ID, "echo test"}, nil)
  692. if err != nil {
  693. t.Fatal(err)
  694. }
  695. shortId, _, err = srv.ContainerCreate(config, "")
  696. if err != nil {
  697. t.Fatal(err)
  698. }
  699. childContainer := runtime.Get(shortId)
  700. if err := runtime.RegisterLink(webapp, childContainer, "db"); err != nil {
  701. t.Fatal(err)
  702. }
  703. children, err := runtime.Children("/webapp")
  704. if err != nil {
  705. t.Fatal(err)
  706. }
  707. if children == nil {
  708. t.Fatal("Children should not be nil")
  709. }
  710. if len(children) == 0 {
  711. t.Fatal("Children should not be empty")
  712. }
  713. for key, value := range children {
  714. if key != "/webapp/db" {
  715. t.Fatalf("Expected /webapp/db got %s", key)
  716. }
  717. if value.ID != childContainer.ID {
  718. t.Fatalf("Expected id %s got %s", childContainer.ID, value.ID)
  719. }
  720. }
  721. }