runtime_test.go 24 KB

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