runtime_test.go 25 KB

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