runtime_test.go 25 KB

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