runtime_test.go 23 KB

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