runtime_test.go 24 KB

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