runtime_test.go 21 KB

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