runtime_test.go 25 KB

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