runtime_test.go 25 KB

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