runtime_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. package docker
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. std_log "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/Sirupsen/logrus"
  18. apiserver "github.com/docker/docker/api/server"
  19. "github.com/docker/docker/cliconfig"
  20. "github.com/docker/docker/daemon"
  21. "github.com/docker/docker/daemon/execdriver"
  22. "github.com/docker/docker/engine"
  23. "github.com/docker/docker/graph"
  24. "github.com/docker/docker/image"
  25. "github.com/docker/docker/nat"
  26. "github.com/docker/docker/pkg/fileutils"
  27. "github.com/docker/docker/pkg/ioutils"
  28. "github.com/docker/docker/pkg/reexec"
  29. "github.com/docker/docker/pkg/stringid"
  30. "github.com/docker/docker/runconfig"
  31. "github.com/docker/docker/utils"
  32. )
  33. const (
  34. unitTestImageName = "docker-test-image"
  35. unitTestImageID = "83599e29c455eb719f77d799bc7c51521b9551972f5a850d7ad265bc1b5292f6" // 1.0
  36. unitTestImageIDShort = "83599e29c455"
  37. unitTestNetworkBridge = "testdockbr0"
  38. unitTestStoreBase = "/var/lib/docker/unit-tests"
  39. unitTestDockerTmpdir = "/var/lib/docker/tmp"
  40. testDaemonAddr = "127.0.0.1:4270"
  41. testDaemonProto = "tcp"
  42. testDaemonHttpsProto = "tcp"
  43. testDaemonHttpsAddr = "localhost:4271"
  44. testDaemonRogueHttpsAddr = "localhost:4272"
  45. )
  46. var (
  47. globalDaemon *daemon.Daemon
  48. globalHttpsEngine *engine.Engine
  49. globalRogueHttpsEngine *engine.Engine
  50. startFds int
  51. startGoroutines int
  52. )
  53. // FIXME: nuke() is deprecated by Daemon.Nuke()
  54. func nuke(daemon *daemon.Daemon) error {
  55. return daemon.Nuke()
  56. }
  57. // FIXME: cleanup and nuke are redundant.
  58. func cleanup(eng *engine.Engine, t *testing.T) error {
  59. daemon := mkDaemonFromEngine(eng, t)
  60. for _, container := range daemon.List() {
  61. container.Kill()
  62. daemon.Rm(container)
  63. }
  64. images, err := daemon.Repositories().Images(&graph.ImagesConfig{})
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. for _, image := range images {
  69. if image.ID != unitTestImageID {
  70. eng.Job("image_delete", image.ID).Run()
  71. }
  72. }
  73. return nil
  74. }
  75. func init() {
  76. // Always use the same driver (vfs) for all integration tests.
  77. // To test other drivers, we need a dedicated driver validation suite.
  78. os.Setenv("DOCKER_DRIVER", "vfs")
  79. os.Setenv("TEST", "1")
  80. os.Setenv("DOCKER_TMPDIR", unitTestDockerTmpdir)
  81. // Hack to run sys init during unit testing
  82. if reexec.Init() {
  83. return
  84. }
  85. if uid := syscall.Geteuid(); uid != 0 {
  86. logrus.Fatalf("docker tests need to be run as root")
  87. }
  88. // Copy dockerinit into our current testing directory, if provided (so we can test a separate dockerinit binary)
  89. if dockerinit := os.Getenv("TEST_DOCKERINIT_PATH"); dockerinit != "" {
  90. src, err := os.Open(dockerinit)
  91. if err != nil {
  92. logrus.Fatalf("Unable to open TEST_DOCKERINIT_PATH: %s", err)
  93. }
  94. defer src.Close()
  95. dst, err := os.OpenFile(filepath.Join(filepath.Dir(utils.SelfPath()), "dockerinit"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0555)
  96. if err != nil {
  97. logrus.Fatalf("Unable to create dockerinit in test directory: %s", err)
  98. }
  99. defer dst.Close()
  100. if _, err := io.Copy(dst, src); err != nil {
  101. logrus.Fatalf("Unable to copy dockerinit to TEST_DOCKERINIT_PATH: %s", err)
  102. }
  103. dst.Close()
  104. src.Close()
  105. }
  106. // Setup the base daemon, which will be duplicated for each test.
  107. // (no tests are run directly in the base)
  108. setupBaseImage()
  109. // Create the "global daemon" with a long-running daemons for integration tests
  110. spawnGlobalDaemon()
  111. startFds, startGoroutines = fileutils.GetTotalUsedFds(), runtime.NumGoroutine()
  112. }
  113. func setupBaseImage() {
  114. eng := newTestEngine(std_log.New(os.Stderr, "", 0), false, unitTestStoreBase)
  115. d := getDaemon(eng)
  116. _, err := d.Repositories().Lookup(unitTestImageName)
  117. // If the unit test is not found, try to download it.
  118. if err != nil {
  119. // seems like we can just ignore the error here...
  120. // there was a check of imgId from job stdout against unittestid but
  121. // if there was an error how could the imgid from the job
  122. // be compared?! it's obvious it's different, am I totally wrong?
  123. // Retrieve the Image
  124. imagePullConfig := &graph.ImagePullConfig{
  125. Parallel: true,
  126. OutStream: ioutils.NopWriteCloser(os.Stdout),
  127. AuthConfig: &cliconfig.AuthConfig{},
  128. }
  129. if err := d.Repositories().Pull(unitTestImageName, "", imagePullConfig); err != nil {
  130. logrus.Fatalf("Unable to pull the test image: %s", err)
  131. }
  132. }
  133. }
  134. func spawnGlobalDaemon() {
  135. if globalDaemon != nil {
  136. logrus.Debugf("Global daemon already exists. Skipping.")
  137. return
  138. }
  139. t := std_log.New(os.Stderr, "", 0)
  140. eng := NewTestEngine(t)
  141. globalDaemon = mkDaemonFromEngine(eng, t)
  142. serverConfig := &apiserver.ServerConfig{Logging: true}
  143. api := apiserver.New(serverConfig, eng)
  144. // Spawn a Daemon
  145. go func() {
  146. logrus.Debugf("Spawning global daemon for integration tests")
  147. listenURL := &url.URL{
  148. Scheme: testDaemonProto,
  149. Host: testDaemonAddr,
  150. }
  151. if err := api.ServeApi([]string{listenURL.String()}); err != nil {
  152. logrus.Fatalf("Unable to spawn the test daemon: %s", err)
  153. }
  154. }()
  155. // Give some time to ListenAndServer to actually start
  156. // FIXME: use inmem transports instead of tcp
  157. time.Sleep(time.Second)
  158. api.AcceptConnections(getDaemon(eng))
  159. }
  160. // FIXME: test that ImagePull(json=true) send correct json output
  161. func GetTestImage(daemon *daemon.Daemon) *image.Image {
  162. imgs, err := daemon.Graph().Map()
  163. if err != nil {
  164. logrus.Fatalf("Unable to get the test image: %s", err)
  165. }
  166. for _, image := range imgs {
  167. if image.ID == unitTestImageID {
  168. return image
  169. }
  170. }
  171. logrus.Fatalf("Test image %v not found in %s: %s", unitTestImageID, daemon.Graph().Root, imgs)
  172. return nil
  173. }
  174. func TestDaemonCreate(t *testing.T) {
  175. daemon := mkDaemon(t)
  176. defer nuke(daemon)
  177. // Make sure we start we 0 containers
  178. if len(daemon.List()) != 0 {
  179. t.Errorf("Expected 0 containers, %v found", len(daemon.List()))
  180. }
  181. container, _, err := daemon.Create(&runconfig.Config{
  182. Image: GetTestImage(daemon).ID,
  183. Cmd: runconfig.NewCommand("ls", "-al"),
  184. },
  185. &runconfig.HostConfig{},
  186. "",
  187. )
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. defer func() {
  192. if err := daemon.Rm(container); err != nil {
  193. t.Error(err)
  194. }
  195. }()
  196. // Make sure we can find the newly created container with List()
  197. if len(daemon.List()) != 1 {
  198. t.Errorf("Expected 1 container, %v found", len(daemon.List()))
  199. }
  200. // Make sure the container List() returns is the right one
  201. if daemon.List()[0].ID != container.ID {
  202. t.Errorf("Unexpected container %v returned by List", daemon.List()[0])
  203. }
  204. // Make sure we can get the container with Get()
  205. if _, err := daemon.Get(container.ID); err != nil {
  206. t.Errorf("Unable to get newly created container")
  207. }
  208. // Make sure it is the right container
  209. if c, _ := daemon.Get(container.ID); c != container {
  210. t.Errorf("Get() returned the wrong container")
  211. }
  212. // Make sure Exists returns it as existing
  213. if !daemon.Exists(container.ID) {
  214. t.Errorf("Exists() returned false for a newly created container")
  215. }
  216. // Test that conflict error displays correct details
  217. cmd := runconfig.NewCommand("ls", "-al")
  218. testContainer, _, _ := daemon.Create(
  219. &runconfig.Config{
  220. Image: GetTestImage(daemon).ID,
  221. Cmd: cmd,
  222. },
  223. &runconfig.HostConfig{},
  224. "conflictname",
  225. )
  226. if _, _, err := daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID, Cmd: cmd}, &runconfig.HostConfig{}, testContainer.Name); err == nil || !strings.Contains(err.Error(), stringid.TruncateID(testContainer.ID)) {
  227. t.Fatalf("Name conflict error doesn't include the correct short id. Message was: %v", err)
  228. }
  229. // Make sure create with bad parameters returns an error
  230. if _, _, err = daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID}, &runconfig.HostConfig{}, ""); err == nil {
  231. t.Fatal("Builder.Create should throw an error when Cmd is missing")
  232. }
  233. if _, _, err := daemon.Create(
  234. &runconfig.Config{
  235. Image: GetTestImage(daemon).ID,
  236. Cmd: runconfig.NewCommand(),
  237. },
  238. &runconfig.HostConfig{},
  239. "",
  240. ); err == nil {
  241. t.Fatal("Builder.Create should throw an error when Cmd is empty")
  242. }
  243. config := &runconfig.Config{
  244. Image: GetTestImage(daemon).ID,
  245. Cmd: runconfig.NewCommand("/bin/ls"),
  246. PortSpecs: []string{"80"},
  247. }
  248. container, _, err = daemon.Create(config, &runconfig.HostConfig{}, "")
  249. _, err = daemon.Commit(container, "testrepo", "testtag", "", "", true, config)
  250. if err != nil {
  251. t.Error(err)
  252. }
  253. // test expose 80:8000
  254. container, warnings, err := daemon.Create(&runconfig.Config{
  255. Image: GetTestImage(daemon).ID,
  256. Cmd: runconfig.NewCommand("ls", "-al"),
  257. PortSpecs: []string{"80:8000"},
  258. },
  259. &runconfig.HostConfig{},
  260. "",
  261. )
  262. if err != nil {
  263. t.Fatal(err)
  264. }
  265. if warnings == nil || len(warnings) != 1 {
  266. t.Error("Expected a warning, got none")
  267. }
  268. }
  269. func TestDestroy(t *testing.T) {
  270. daemon := mkDaemon(t)
  271. defer nuke(daemon)
  272. container, _, err := daemon.Create(&runconfig.Config{
  273. Image: GetTestImage(daemon).ID,
  274. Cmd: runconfig.NewCommand("ls", "-al"),
  275. },
  276. &runconfig.HostConfig{},
  277. "")
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. // Destroy
  282. if err := daemon.Rm(container); err != nil {
  283. t.Error(err)
  284. }
  285. // Make sure daemon.Exists() behaves correctly
  286. if daemon.Exists("test_destroy") {
  287. t.Errorf("Exists() returned true")
  288. }
  289. // Make sure daemon.List() doesn't list the destroyed container
  290. if len(daemon.List()) != 0 {
  291. t.Errorf("Expected 0 container, %v found", len(daemon.List()))
  292. }
  293. // Make sure daemon.Get() refuses to return the unexisting container
  294. if c, _ := daemon.Get(container.ID); c != nil {
  295. t.Errorf("Got a container that should not exist")
  296. }
  297. // Test double destroy
  298. if err := daemon.Rm(container); err == nil {
  299. // It should have failed
  300. t.Errorf("Double destroy did not fail")
  301. }
  302. }
  303. func TestGet(t *testing.T) {
  304. daemon := mkDaemon(t)
  305. defer nuke(daemon)
  306. container1, _, _ := mkContainer(daemon, []string{"_", "ls", "-al"}, t)
  307. defer daemon.Rm(container1)
  308. container2, _, _ := mkContainer(daemon, []string{"_", "ls", "-al"}, t)
  309. defer daemon.Rm(container2)
  310. container3, _, _ := mkContainer(daemon, []string{"_", "ls", "-al"}, t)
  311. defer daemon.Rm(container3)
  312. if c, _ := daemon.Get(container1.ID); c != container1 {
  313. t.Errorf("Get(test1) returned %v while expecting %v", c, container1)
  314. }
  315. if c, _ := daemon.Get(container2.ID); c != container2 {
  316. t.Errorf("Get(test2) returned %v while expecting %v", c, container2)
  317. }
  318. if c, _ := daemon.Get(container3.ID); c != container3 {
  319. t.Errorf("Get(test3) returned %v while expecting %v", c, container3)
  320. }
  321. }
  322. func startEchoServerContainer(t *testing.T, proto string) (*daemon.Daemon, *daemon.Container, string) {
  323. var (
  324. err error
  325. id string
  326. strPort string
  327. eng = NewTestEngine(t)
  328. daemon = mkDaemonFromEngine(eng, t)
  329. port = 5554
  330. p nat.Port
  331. )
  332. defer func() {
  333. if err != nil {
  334. daemon.Nuke()
  335. }
  336. }()
  337. for {
  338. port += 1
  339. strPort = strconv.Itoa(port)
  340. var cmd string
  341. if proto == "tcp" {
  342. cmd = "socat TCP-LISTEN:" + strPort + ",reuseaddr,fork EXEC:/bin/cat"
  343. } else if proto == "udp" {
  344. cmd = "socat UDP-RECVFROM:" + strPort + ",fork EXEC:/bin/cat"
  345. } else {
  346. t.Fatal(fmt.Errorf("Unknown protocol %v", proto))
  347. }
  348. ep := make(map[nat.Port]struct{}, 1)
  349. p = nat.Port(fmt.Sprintf("%s/%s", strPort, proto))
  350. ep[p] = struct{}{}
  351. c := &runconfig.Config{
  352. Image: unitTestImageID,
  353. Cmd: runconfig.NewCommand("sh", "-c", cmd),
  354. PortSpecs: []string{fmt.Sprintf("%s/%s", strPort, proto)},
  355. ExposedPorts: ep,
  356. }
  357. id, _, err = daemon.ContainerCreate(unitTestImageID, c, &runconfig.HostConfig{})
  358. // FIXME: this relies on the undocumented behavior of daemon.Create
  359. // which will return a nil error AND container if the exposed ports
  360. // are invalid. That behavior should be fixed!
  361. if id != "" {
  362. break
  363. }
  364. t.Logf("Port %v already in use, trying another one", strPort)
  365. }
  366. if err := daemon.ContainerStart(id, &runconfig.HostConfig{}); err != nil {
  367. t.Fatal(err)
  368. }
  369. container, err := daemon.Get(id)
  370. if err != nil {
  371. t.Fatal(err)
  372. }
  373. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  374. for !container.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.WaitStop(500 * time.Millisecond)
  380. strPort = container.NetworkSettings.Ports[p][0].HostPort
  381. return daemon, 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. daemon, container, port := startEchoServerContainer(t, "tcp")
  386. defer nuke(daemon)
  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. daemon, container, port := startEchoServerContainer(t, "udp")
  431. defer nuke(daemon)
  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. daemon1 := mkDaemonFromEngine(eng, t)
  463. defer daemon1.Nuke()
  464. // Create a container with one instance of docker
  465. container1, _, _ := mkContainer(daemon1, []string{"_", "ls", "-al"}, t)
  466. defer daemon1.Rm(container1)
  467. // Create a second container meant to be killed
  468. container2, _, _ := mkContainer(daemon1, []string{"-i", "_", "/bin/cat"}, t)
  469. defer daemon1.Rm(container2)
  470. // Start the container non blocking
  471. if err := container2.Start(); err != nil {
  472. t.Fatal(err)
  473. }
  474. if !container2.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.WaitStop(2 * time.Second); err != nil {
  481. t.Fatal(err)
  482. }
  483. container2.SetRunning(42)
  484. container2.ToDisk()
  485. if len(daemon1.List()) != 2 {
  486. t.Errorf("Expected 2 container, %v found", len(daemon1.List()))
  487. }
  488. if err := container1.Run(); err != nil {
  489. t.Fatal(err)
  490. }
  491. if !container2.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. eng = newTestEngine(t, false, daemon1.Config().Root)
  497. daemon2 := mkDaemonFromEngine(eng, t)
  498. if len(daemon2.List()) != 2 {
  499. t.Errorf("Expected 2 container, %v found", len(daemon2.List()))
  500. }
  501. runningCount := 0
  502. for _, c := range daemon2.List() {
  503. if c.IsRunning() {
  504. t.Errorf("Running container found: %v (%v)", c.ID, c.Path)
  505. runningCount++
  506. }
  507. }
  508. if runningCount != 0 {
  509. t.Fatalf("Expected 0 container alive, %d found", runningCount)
  510. }
  511. container3, err := daemon2.Get(container1.ID)
  512. if err != nil {
  513. t.Fatal("Unable to Get container")
  514. }
  515. if err := container3.Run(); err != nil {
  516. t.Fatal(err)
  517. }
  518. container2.SetStopped(&execdriver.ExitStatus{ExitCode: 0})
  519. }
  520. func TestDefaultContainerName(t *testing.T) {
  521. eng := NewTestEngine(t)
  522. daemon := mkDaemonFromEngine(eng, t)
  523. defer nuke(daemon)
  524. config, _, _, err := parseRun([]string{unitTestImageID, "echo test"})
  525. if err != nil {
  526. t.Fatal(err)
  527. }
  528. container, err := daemon.Get(createNamedTestContainer(eng, config, t, "some_name"))
  529. if err != nil {
  530. t.Fatal(err)
  531. }
  532. containerID := container.ID
  533. if container.Name != "/some_name" {
  534. t.Fatalf("Expect /some_name got %s", container.Name)
  535. }
  536. c, err := daemon.Get("/some_name")
  537. if err != nil {
  538. t.Fatalf("Couldn't retrieve test container as /some_name")
  539. }
  540. if c.ID != containerID {
  541. t.Fatalf("Container /some_name has ID %s instead of %s", c.ID, containerID)
  542. }
  543. }
  544. func TestRandomContainerName(t *testing.T) {
  545. eng := NewTestEngine(t)
  546. daemon := mkDaemonFromEngine(eng, t)
  547. defer nuke(daemon)
  548. config, _, _, err := parseRun([]string{GetTestImage(daemon).ID, "echo test"})
  549. if err != nil {
  550. t.Fatal(err)
  551. }
  552. container, err := daemon.Get(createTestContainer(eng, config, t))
  553. if err != nil {
  554. t.Fatal(err)
  555. }
  556. containerID := container.ID
  557. if container.Name == "" {
  558. t.Fatalf("Expected not empty container name")
  559. }
  560. if c, err := daemon.Get(container.Name); err != nil {
  561. logrus.Fatalf("Could not lookup container %s by its name", container.Name)
  562. } else if c.ID != containerID {
  563. logrus.Fatalf("Looking up container name %s returned id %s instead of %s", container.Name, c.ID, containerID)
  564. }
  565. }
  566. func TestContainerNameValidation(t *testing.T) {
  567. eng := NewTestEngine(t)
  568. daemon := mkDaemonFromEngine(eng, t)
  569. defer nuke(daemon)
  570. for _, test := range []struct {
  571. Name string
  572. Valid bool
  573. }{
  574. {"abc-123_AAA.1", true},
  575. {"\000asdf", false},
  576. } {
  577. config, _, _, err := parseRun([]string{unitTestImageID, "echo test"})
  578. if err != nil {
  579. if !test.Valid {
  580. continue
  581. }
  582. t.Fatal(err)
  583. }
  584. containerId, _, err := daemon.ContainerCreate(test.Name, config, &runconfig.HostConfig{})
  585. if err != nil {
  586. if !test.Valid {
  587. continue
  588. }
  589. t.Fatal(err)
  590. }
  591. container, err := daemon.Get(containerId)
  592. if err != nil {
  593. t.Fatal(err)
  594. }
  595. if container.Name != "/"+test.Name {
  596. t.Fatalf("Expect /%s got %s", test.Name, container.Name)
  597. }
  598. if c, err := daemon.Get("/" + test.Name); err != nil {
  599. t.Fatalf("Couldn't retrieve test container as /%s", test.Name)
  600. } else if c.ID != container.ID {
  601. t.Fatalf("Container /%s has ID %s instead of %s", test.Name, c.ID, container.ID)
  602. }
  603. }
  604. }
  605. func TestLinkChildContainer(t *testing.T) {
  606. eng := NewTestEngine(t)
  607. daemon := mkDaemonFromEngine(eng, t)
  608. defer nuke(daemon)
  609. config, _, _, err := parseRun([]string{unitTestImageID, "echo test"})
  610. if err != nil {
  611. t.Fatal(err)
  612. }
  613. container, err := daemon.Get(createNamedTestContainer(eng, config, t, "/webapp"))
  614. if err != nil {
  615. t.Fatal(err)
  616. }
  617. webapp, err := daemon.GetByName("/webapp")
  618. if err != nil {
  619. t.Fatal(err)
  620. }
  621. if webapp.ID != container.ID {
  622. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  623. }
  624. config, _, _, err = parseRun([]string{GetTestImage(daemon).ID, "echo test"})
  625. if err != nil {
  626. t.Fatal(err)
  627. }
  628. childContainer, err := daemon.Get(createTestContainer(eng, config, t))
  629. if err != nil {
  630. t.Fatal(err)
  631. }
  632. if err := daemon.RegisterLink(webapp, childContainer, "db"); err != nil {
  633. t.Fatal(err)
  634. }
  635. // Get the child by it's new name
  636. db, err := daemon.GetByName("/webapp/db")
  637. if err != nil {
  638. t.Fatal(err)
  639. }
  640. if db.ID != childContainer.ID {
  641. t.Fatalf("Expect db id to match container id: %s != %s", db.ID, childContainer.ID)
  642. }
  643. }
  644. func TestGetAllChildren(t *testing.T) {
  645. eng := NewTestEngine(t)
  646. daemon := mkDaemonFromEngine(eng, t)
  647. defer nuke(daemon)
  648. config, _, _, err := parseRun([]string{unitTestImageID, "echo test"})
  649. if err != nil {
  650. t.Fatal(err)
  651. }
  652. container, err := daemon.Get(createNamedTestContainer(eng, config, t, "/webapp"))
  653. if err != nil {
  654. t.Fatal(err)
  655. }
  656. webapp, err := daemon.GetByName("/webapp")
  657. if err != nil {
  658. t.Fatal(err)
  659. }
  660. if webapp.ID != container.ID {
  661. t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID)
  662. }
  663. config, _, _, err = parseRun([]string{unitTestImageID, "echo test"})
  664. if err != nil {
  665. t.Fatal(err)
  666. }
  667. childContainer, err := daemon.Get(createTestContainer(eng, config, t))
  668. if err != nil {
  669. t.Fatal(err)
  670. }
  671. if err := daemon.RegisterLink(webapp, childContainer, "db"); err != nil {
  672. t.Fatal(err)
  673. }
  674. children, err := daemon.Children("/webapp")
  675. if err != nil {
  676. t.Fatal(err)
  677. }
  678. if children == nil {
  679. t.Fatal("Children should not be nil")
  680. }
  681. if len(children) == 0 {
  682. t.Fatal("Children should not be empty")
  683. }
  684. for key, value := range children {
  685. if key != "/webapp/db" {
  686. t.Fatalf("Expected /webapp/db got %s", key)
  687. }
  688. if value.ID != childContainer.ID {
  689. t.Fatalf("Expected id %s got %s", childContainer.ID, value.ID)
  690. }
  691. }
  692. }
  693. func TestDestroyWithInitLayer(t *testing.T) {
  694. daemon := mkDaemon(t)
  695. defer nuke(daemon)
  696. container, _, err := daemon.Create(&runconfig.Config{
  697. Image: GetTestImage(daemon).ID,
  698. Cmd: runconfig.NewCommand("ls", "-al"),
  699. },
  700. &runconfig.HostConfig{},
  701. "")
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. // Destroy
  706. if err := daemon.Rm(container); err != nil {
  707. t.Fatal(err)
  708. }
  709. // Make sure daemon.Exists() behaves correctly
  710. if daemon.Exists("test_destroy") {
  711. t.Fatalf("Exists() returned true")
  712. }
  713. // Make sure daemon.List() doesn't list the destroyed container
  714. if len(daemon.List()) != 0 {
  715. t.Fatalf("Expected 0 container, %v found", len(daemon.List()))
  716. }
  717. driver := daemon.Graph().Driver()
  718. // Make sure that the container does not exist in the driver
  719. if _, err := driver.Get(container.ID, ""); err == nil {
  720. t.Fatal("Container should not exist in the driver")
  721. }
  722. // Make sure that the init layer is removed from the driver
  723. if _, err := driver.Get(fmt.Sprintf("%s-init", container.ID), ""); err == nil {
  724. t.Fatal("Container's init layer should not exist in the driver")
  725. }
  726. }