docker_utils.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/http/httputil"
  13. "net/url"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. "time"
  22. "github.com/docker/docker/api"
  23. "github.com/docker/docker/pkg/ioutils"
  24. "github.com/docker/docker/pkg/stringutils"
  25. )
  26. // Daemon represents a Docker daemon for the testing framework.
  27. type Daemon struct {
  28. t *testing.T
  29. logFile *os.File
  30. folder string
  31. stdin io.WriteCloser
  32. stdout, stderr io.ReadCloser
  33. cmd *exec.Cmd
  34. storageDriver string
  35. execDriver string
  36. wait chan error
  37. }
  38. // NewDaemon returns a Daemon instance to be used for testing.
  39. // This will create a directory such as daemon123456789 in the folder specified by $DEST.
  40. // The daemon will not automatically start.
  41. func NewDaemon(t *testing.T) *Daemon {
  42. dest := os.Getenv("DEST")
  43. if dest == "" {
  44. t.Fatal("Please set the DEST environment variable")
  45. }
  46. dir := filepath.Join(dest, fmt.Sprintf("daemon%d", time.Now().UnixNano()%100000000))
  47. daemonFolder, err := filepath.Abs(dir)
  48. if err != nil {
  49. t.Fatalf("Could not make %q an absolute path: %v", dir, err)
  50. }
  51. if err := os.MkdirAll(filepath.Join(daemonFolder, "graph"), 0600); err != nil {
  52. t.Fatalf("Could not create %s/graph directory", daemonFolder)
  53. }
  54. return &Daemon{
  55. t: t,
  56. folder: daemonFolder,
  57. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  58. execDriver: os.Getenv("DOCKER_EXECDRIVER"),
  59. }
  60. }
  61. // Start will start the daemon and return once it is ready to receive requests.
  62. // You can specify additional daemon flags.
  63. func (d *Daemon) Start(arg ...string) error {
  64. dockerBinary, err := exec.LookPath(dockerBinary)
  65. if err != nil {
  66. d.t.Fatalf("could not find docker binary in $PATH: %v", err)
  67. }
  68. args := []string{
  69. "--host", d.sock(),
  70. "--daemon",
  71. "--graph", fmt.Sprintf("%s/graph", d.folder),
  72. "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
  73. }
  74. // If we don't explicitly set the log-level or debug flag(-D) then
  75. // turn on debug mode
  76. foundIt := false
  77. for _, a := range arg {
  78. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") {
  79. foundIt = true
  80. }
  81. }
  82. if !foundIt {
  83. args = append(args, "--debug")
  84. }
  85. if d.storageDriver != "" {
  86. args = append(args, "--storage-driver", d.storageDriver)
  87. }
  88. if d.execDriver != "" {
  89. args = append(args, "--exec-driver", d.execDriver)
  90. }
  91. args = append(args, arg...)
  92. d.cmd = exec.Command(dockerBinary, args...)
  93. d.logFile, err = os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  94. if err != nil {
  95. d.t.Fatalf("Could not create %s/docker.log: %v", d.folder, err)
  96. }
  97. d.cmd.Stdout = d.logFile
  98. d.cmd.Stderr = d.logFile
  99. if err := d.cmd.Start(); err != nil {
  100. return fmt.Errorf("could not start daemon container: %v", err)
  101. }
  102. wait := make(chan error)
  103. go func() {
  104. wait <- d.cmd.Wait()
  105. d.t.Log("exiting daemon")
  106. close(wait)
  107. }()
  108. d.wait = wait
  109. tick := time.Tick(500 * time.Millisecond)
  110. // make sure daemon is ready to receive requests
  111. startTime := time.Now().Unix()
  112. for {
  113. d.t.Log("waiting for daemon to start")
  114. if time.Now().Unix()-startTime > 5 {
  115. // After 5 seconds, give up
  116. return errors.New("Daemon exited and never started")
  117. }
  118. select {
  119. case <-time.After(2 * time.Second):
  120. return errors.New("timeout: daemon does not respond")
  121. case <-tick:
  122. c, err := net.Dial("unix", filepath.Join(d.folder, "docker.sock"))
  123. if err != nil {
  124. continue
  125. }
  126. client := httputil.NewClientConn(c, nil)
  127. defer client.Close()
  128. req, err := http.NewRequest("GET", "/_ping", nil)
  129. if err != nil {
  130. d.t.Fatalf("could not create new request: %v", err)
  131. }
  132. resp, err := client.Do(req)
  133. if err != nil {
  134. continue
  135. }
  136. if resp.StatusCode != http.StatusOK {
  137. d.t.Logf("received status != 200 OK: %s", resp.Status)
  138. }
  139. d.t.Log("daemon started")
  140. return nil
  141. }
  142. }
  143. }
  144. // StartWithBusybox will first start the daemon with Daemon.Start()
  145. // then save the busybox image from the main daemon and load it into this Daemon instance.
  146. func (d *Daemon) StartWithBusybox(arg ...string) error {
  147. if err := d.Start(arg...); err != nil {
  148. return err
  149. }
  150. bb := filepath.Join(d.folder, "busybox.tar")
  151. if _, err := os.Stat(bb); err != nil {
  152. if !os.IsNotExist(err) {
  153. return fmt.Errorf("unexpected error on busybox.tar stat: %v", err)
  154. }
  155. // saving busybox image from main daemon
  156. if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil {
  157. return fmt.Errorf("could not save busybox image: %v", err)
  158. }
  159. }
  160. // loading busybox image to this daemon
  161. if _, err := d.Cmd("load", "--input", bb); err != nil {
  162. return fmt.Errorf("could not load busybox image: %v", err)
  163. }
  164. if err := os.Remove(bb); err != nil {
  165. d.t.Logf("Could not remove %s: %v", bb, err)
  166. }
  167. return nil
  168. }
  169. // Stop will send a SIGINT every second and wait for the daemon to stop.
  170. // If it timeouts, a SIGKILL is sent.
  171. // Stop will not delete the daemon directory. If a purged daemon is needed,
  172. // instantiate a new one with NewDaemon.
  173. func (d *Daemon) Stop() error {
  174. if d.cmd == nil || d.wait == nil {
  175. return errors.New("daemon not started")
  176. }
  177. defer func() {
  178. d.logFile.Close()
  179. d.cmd = nil
  180. }()
  181. i := 1
  182. tick := time.Tick(time.Second)
  183. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  184. return fmt.Errorf("could not send signal: %v", err)
  185. }
  186. out1:
  187. for {
  188. select {
  189. case err := <-d.wait:
  190. return err
  191. case <-time.After(15 * time.Second):
  192. // time for stopping jobs and run onShutdown hooks
  193. d.t.Log("timeout")
  194. break out1
  195. }
  196. }
  197. out2:
  198. for {
  199. select {
  200. case err := <-d.wait:
  201. return err
  202. case <-tick:
  203. i++
  204. if i > 4 {
  205. d.t.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  206. break out2
  207. }
  208. d.t.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  209. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  210. return fmt.Errorf("could not send signal: %v", err)
  211. }
  212. }
  213. }
  214. if err := d.cmd.Process.Kill(); err != nil {
  215. d.t.Logf("Could not kill daemon: %v", err)
  216. return err
  217. }
  218. return nil
  219. }
  220. // Restart will restart the daemon by first stopping it and then starting it.
  221. func (d *Daemon) Restart(arg ...string) error {
  222. d.Stop()
  223. return d.Start(arg...)
  224. }
  225. func (d *Daemon) sock() string {
  226. return fmt.Sprintf("unix://%s/docker.sock", d.folder)
  227. }
  228. // Cmd will execute a docker CLI command against this Daemon.
  229. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  230. func (d *Daemon) Cmd(name string, arg ...string) (string, error) {
  231. args := []string{"--host", d.sock(), name}
  232. args = append(args, arg...)
  233. c := exec.Command(dockerBinary, args...)
  234. b, err := c.CombinedOutput()
  235. return string(b), err
  236. }
  237. func (d *Daemon) LogfileName() string {
  238. return d.logFile.Name()
  239. }
  240. func daemonHost() string {
  241. daemonUrlStr := "unix://" + api.DEFAULTUNIXSOCKET
  242. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  243. daemonUrlStr = daemonHostVar
  244. }
  245. return daemonUrlStr
  246. }
  247. func sockConn(timeout time.Duration) (net.Conn, error) {
  248. daemon := daemonHost()
  249. daemonUrl, err := url.Parse(daemon)
  250. if err != nil {
  251. return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
  252. }
  253. var c net.Conn
  254. switch daemonUrl.Scheme {
  255. case "unix":
  256. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Path, timeout)
  257. case "tcp":
  258. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Host, timeout)
  259. default:
  260. return c, fmt.Errorf("unknown scheme %v (%s)", daemonUrl.Scheme, daemon)
  261. }
  262. }
  263. func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  264. jsonData := bytes.NewBuffer(nil)
  265. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  266. return -1, nil, err
  267. }
  268. status, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
  269. if err != nil {
  270. b, _ := ioutil.ReadAll(body)
  271. return status, b, err
  272. }
  273. var b []byte
  274. b, err = readBody(body)
  275. return status, b, err
  276. }
  277. func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (int, io.ReadCloser, error) {
  278. c, err := sockConn(time.Duration(10 * time.Second))
  279. if err != nil {
  280. return -1, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  281. }
  282. client := httputil.NewClientConn(c, nil)
  283. req, err := http.NewRequest(method, endpoint, data)
  284. if err != nil {
  285. client.Close()
  286. return -1, nil, fmt.Errorf("could not create new request: %v", err)
  287. }
  288. if ct == "" {
  289. ct = "application/json"
  290. }
  291. req.Header.Set("Content-Type", ct)
  292. resp, err := client.Do(req)
  293. if err != nil {
  294. client.Close()
  295. return -1, nil, fmt.Errorf("could not perform request: %v", err)
  296. }
  297. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  298. defer client.Close()
  299. return resp.Body.Close()
  300. })
  301. if resp.StatusCode != http.StatusOK {
  302. return resp.StatusCode, body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
  303. }
  304. return resp.StatusCode, body, err
  305. }
  306. func readBody(b io.ReadCloser) ([]byte, error) {
  307. defer b.Close()
  308. return ioutil.ReadAll(b)
  309. }
  310. func deleteContainer(container string) error {
  311. container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
  312. killArgs := strings.Split(fmt.Sprintf("kill %v", container), " ")
  313. runCommand(exec.Command(dockerBinary, killArgs...))
  314. rmArgs := strings.Split(fmt.Sprintf("rm -v %v", container), " ")
  315. exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
  316. // set error manually if not set
  317. if exitCode != 0 && err == nil {
  318. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  319. }
  320. return err
  321. }
  322. func getAllContainers() (string, error) {
  323. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  324. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  325. if exitCode != 0 && err == nil {
  326. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  327. }
  328. return out, err
  329. }
  330. func deleteAllContainers() error {
  331. containers, err := getAllContainers()
  332. if err != nil {
  333. fmt.Println(containers)
  334. return err
  335. }
  336. if err = deleteContainer(containers); err != nil {
  337. return err
  338. }
  339. return nil
  340. }
  341. func getPausedContainers() (string, error) {
  342. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  343. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  344. if exitCode != 0 && err == nil {
  345. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  346. }
  347. return out, err
  348. }
  349. func getSliceOfPausedContainers() ([]string, error) {
  350. out, err := getPausedContainers()
  351. if err == nil {
  352. if len(out) == 0 {
  353. return nil, err
  354. }
  355. slice := strings.Split(strings.TrimSpace(out), "\n")
  356. return slice, err
  357. }
  358. return []string{out}, err
  359. }
  360. func unpauseContainer(container string) error {
  361. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  362. exitCode, err := runCommand(unpauseCmd)
  363. if exitCode != 0 && err == nil {
  364. err = fmt.Errorf("failed to unpause container")
  365. }
  366. return nil
  367. }
  368. func unpauseAllContainers() error {
  369. containers, err := getPausedContainers()
  370. if err != nil {
  371. fmt.Println(containers)
  372. return err
  373. }
  374. containers = strings.Replace(containers, "\n", " ", -1)
  375. containers = strings.Trim(containers, " ")
  376. containerList := strings.Split(containers, " ")
  377. for _, value := range containerList {
  378. if err = unpauseContainer(value); err != nil {
  379. return err
  380. }
  381. }
  382. return nil
  383. }
  384. func deleteImages(images ...string) error {
  385. args := make([]string, 1, 2)
  386. args[0] = "rmi"
  387. args = append(args, images...)
  388. rmiCmd := exec.Command(dockerBinary, args...)
  389. exitCode, err := runCommand(rmiCmd)
  390. // set error manually if not set
  391. if exitCode != 0 && err == nil {
  392. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  393. }
  394. return err
  395. }
  396. func imageExists(image string) error {
  397. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  398. exitCode, err := runCommand(inspectCmd)
  399. if exitCode != 0 && err == nil {
  400. err = fmt.Errorf("couldn't find image %q", image)
  401. }
  402. return err
  403. }
  404. func pullImageIfNotExist(image string) (err error) {
  405. if err := imageExists(image); err != nil {
  406. pullCmd := exec.Command(dockerBinary, "pull", image)
  407. _, exitCode, err := runCommandWithOutput(pullCmd)
  408. if err != nil || exitCode != 0 {
  409. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  410. }
  411. }
  412. return
  413. }
  414. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  415. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  416. if err != nil {
  417. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  418. }
  419. return out, status, err
  420. }
  421. // execute a docker command with a timeout
  422. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  423. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  424. if err != nil {
  425. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  426. }
  427. return out, status, err
  428. }
  429. // execute a docker command in a directory
  430. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  431. dockerCommand := exec.Command(dockerBinary, args...)
  432. dockerCommand.Dir = path
  433. out, status, err := runCommandWithOutput(dockerCommand)
  434. if err != nil {
  435. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  436. }
  437. return out, status, err
  438. }
  439. // execute a docker command in a directory with a timeout
  440. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  441. dockerCommand := exec.Command(dockerBinary, args...)
  442. dockerCommand.Dir = path
  443. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  444. if err != nil {
  445. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  446. }
  447. return out, status, err
  448. }
  449. func findContainerIP(t *testing.T, id string) string {
  450. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  451. out, _, err := runCommandWithOutput(cmd)
  452. if err != nil {
  453. t.Fatal(err, out)
  454. }
  455. return strings.Trim(out, " \r\n'")
  456. }
  457. func getContainerCount() (int, error) {
  458. const containers = "Containers:"
  459. cmd := exec.Command(dockerBinary, "info")
  460. out, _, err := runCommandWithOutput(cmd)
  461. if err != nil {
  462. return 0, err
  463. }
  464. lines := strings.Split(out, "\n")
  465. for _, line := range lines {
  466. if strings.Contains(line, containers) {
  467. output := strings.TrimSpace(line)
  468. output = strings.TrimLeft(output, containers)
  469. output = strings.Trim(output, " ")
  470. containerCount, err := strconv.Atoi(output)
  471. if err != nil {
  472. return 0, err
  473. }
  474. return containerCount, nil
  475. }
  476. }
  477. return 0, fmt.Errorf("couldn't find the Container count in the output")
  478. }
  479. type FakeContext struct {
  480. Dir string
  481. }
  482. func (f *FakeContext) Add(file, content string) error {
  483. filepath := path.Join(f.Dir, file)
  484. dirpath := path.Dir(filepath)
  485. if dirpath != "." {
  486. if err := os.MkdirAll(dirpath, 0755); err != nil {
  487. return err
  488. }
  489. }
  490. return ioutil.WriteFile(filepath, []byte(content), 0644)
  491. }
  492. func (f *FakeContext) Delete(file string) error {
  493. filepath := path.Join(f.Dir, file)
  494. return os.RemoveAll(filepath)
  495. }
  496. func (f *FakeContext) Close() error {
  497. return os.RemoveAll(f.Dir)
  498. }
  499. func fakeContextFromDir(dir string) *FakeContext {
  500. return &FakeContext{dir}
  501. }
  502. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  503. tmp, err := ioutil.TempDir("", "fake-context")
  504. if err != nil {
  505. return nil, err
  506. }
  507. if err := os.Chmod(tmp, 0755); err != nil {
  508. return nil, err
  509. }
  510. ctx := fakeContextFromDir(tmp)
  511. for file, content := range files {
  512. if err := ctx.Add(file, content); err != nil {
  513. ctx.Close()
  514. return nil, err
  515. }
  516. }
  517. return ctx, nil
  518. }
  519. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  520. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  521. ctx.Close()
  522. return err
  523. }
  524. return nil
  525. }
  526. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  527. ctx, err := fakeContextWithFiles(files)
  528. if err != nil {
  529. ctx.Close()
  530. return nil, err
  531. }
  532. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  533. return nil, err
  534. }
  535. return ctx, nil
  536. }
  537. // FakeStorage is a static file server. It might be running locally or remotely
  538. // on test host.
  539. type FakeStorage interface {
  540. Close() error
  541. URL() string
  542. CtxDir() string
  543. }
  544. // fakeStorage returns either a local or remote (at daemon machine) file server
  545. func fakeStorage(files map[string]string) (FakeStorage, error) {
  546. ctx, err := fakeContextWithFiles(files)
  547. if err != nil {
  548. return nil, err
  549. }
  550. return fakeStorageWithContext(ctx)
  551. }
  552. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  553. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  554. if isLocalDaemon {
  555. return newLocalFakeStorage(ctx)
  556. }
  557. return newRemoteFileServer(ctx)
  558. }
  559. // localFileStorage is a file storage on the running machine
  560. type localFileStorage struct {
  561. *FakeContext
  562. *httptest.Server
  563. }
  564. func (s *localFileStorage) URL() string {
  565. return s.Server.URL
  566. }
  567. func (s *localFileStorage) CtxDir() string {
  568. return s.FakeContext.Dir
  569. }
  570. func (s *localFileStorage) Close() error {
  571. defer s.Server.Close()
  572. return s.FakeContext.Close()
  573. }
  574. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  575. handler := http.FileServer(http.Dir(ctx.Dir))
  576. server := httptest.NewServer(handler)
  577. return &localFileStorage{
  578. FakeContext: ctx,
  579. Server: server,
  580. }, nil
  581. }
  582. // remoteFileServer is a containerized static file server started on the remote
  583. // testing machine to be used in URL-accepting docker build functionality.
  584. type remoteFileServer struct {
  585. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  586. container string
  587. image string
  588. ctx *FakeContext
  589. }
  590. func (f *remoteFileServer) URL() string {
  591. u := url.URL{
  592. Scheme: "http",
  593. Host: f.host}
  594. return u.String()
  595. }
  596. func (f *remoteFileServer) CtxDir() string {
  597. return f.ctx.Dir
  598. }
  599. func (f *remoteFileServer) Close() error {
  600. defer func() {
  601. if f.ctx != nil {
  602. f.ctx.Close()
  603. }
  604. if f.image != "" {
  605. deleteImages(f.image)
  606. }
  607. }()
  608. if f.container == "" {
  609. return nil
  610. }
  611. return deleteContainer(f.container)
  612. }
  613. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  614. var (
  615. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  616. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  617. )
  618. // Build the image
  619. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  620. COPY . /static`); err != nil {
  621. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  622. }
  623. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  624. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  625. }
  626. // Start the container
  627. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  628. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  629. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  630. }
  631. // Find out the system assigned port
  632. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  633. if err != nil {
  634. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  635. }
  636. return &remoteFileServer{
  637. container: container,
  638. image: image,
  639. host: strings.Trim(out, "\n"),
  640. ctx: ctx}, nil
  641. }
  642. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  643. str, err := inspectFieldJSON(name, field)
  644. if err != nil {
  645. return err
  646. }
  647. return json.Unmarshal([]byte(str), output)
  648. }
  649. func inspectFilter(name, filter string) (string, error) {
  650. format := fmt.Sprintf("{{%s}}", filter)
  651. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  652. out, exitCode, err := runCommandWithOutput(inspectCmd)
  653. if err != nil || exitCode != 0 {
  654. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  655. }
  656. return strings.TrimSpace(out), nil
  657. }
  658. func inspectField(name, field string) (string, error) {
  659. return inspectFilter(name, fmt.Sprintf(".%s", field))
  660. }
  661. func inspectFieldJSON(name, field string) (string, error) {
  662. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  663. }
  664. func inspectFieldMap(name, path, field string) (string, error) {
  665. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  666. }
  667. func getIDByName(name string) (string, error) {
  668. return inspectField(name, "Id")
  669. }
  670. // getContainerState returns the exit code of the container
  671. // and true if it's running
  672. // the exit code should be ignored if it's running
  673. func getContainerState(t *testing.T, id string) (int, bool, error) {
  674. var (
  675. exitStatus int
  676. running bool
  677. )
  678. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  679. if err != nil || exitCode != 0 {
  680. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  681. }
  682. out = strings.Trim(out, "\n")
  683. splitOutput := strings.Split(out, " ")
  684. if len(splitOutput) != 2 {
  685. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  686. }
  687. if splitOutput[0] == "true" {
  688. running = true
  689. }
  690. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  691. exitStatus = n
  692. } else {
  693. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  694. }
  695. return exitStatus, running, nil
  696. }
  697. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  698. args := []string{"build", "-t", name}
  699. if !useCache {
  700. args = append(args, "--no-cache")
  701. }
  702. args = append(args, "-")
  703. buildCmd := exec.Command(dockerBinary, args...)
  704. buildCmd.Stdin = strings.NewReader(dockerfile)
  705. out, exitCode, err := runCommandWithOutput(buildCmd)
  706. if err != nil || exitCode != 0 {
  707. return "", out, fmt.Errorf("failed to build the image: %s", out)
  708. }
  709. id, err := getIDByName(name)
  710. if err != nil {
  711. return "", out, err
  712. }
  713. return id, out, nil
  714. }
  715. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  716. args := []string{"build", "-t", name}
  717. if !useCache {
  718. args = append(args, "--no-cache")
  719. }
  720. args = append(args, "-")
  721. buildCmd := exec.Command(dockerBinary, args...)
  722. buildCmd.Stdin = strings.NewReader(dockerfile)
  723. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  724. if err != nil || exitCode != 0 {
  725. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  726. }
  727. id, err := getIDByName(name)
  728. if err != nil {
  729. return "", stdout, stderr, err
  730. }
  731. return id, stdout, stderr, nil
  732. }
  733. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  734. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  735. return id, err
  736. }
  737. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  738. args := []string{"build", "-t", name}
  739. if !useCache {
  740. args = append(args, "--no-cache")
  741. }
  742. args = append(args, ".")
  743. buildCmd := exec.Command(dockerBinary, args...)
  744. buildCmd.Dir = ctx.Dir
  745. out, exitCode, err := runCommandWithOutput(buildCmd)
  746. if err != nil || exitCode != 0 {
  747. return "", fmt.Errorf("failed to build the image: %s", out)
  748. }
  749. return getIDByName(name)
  750. }
  751. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  752. args := []string{"build", "-t", name}
  753. if !useCache {
  754. args = append(args, "--no-cache")
  755. }
  756. args = append(args, path)
  757. buildCmd := exec.Command(dockerBinary, args...)
  758. out, exitCode, err := runCommandWithOutput(buildCmd)
  759. if err != nil || exitCode != 0 {
  760. return "", fmt.Errorf("failed to build the image: %s", out)
  761. }
  762. return getIDByName(name)
  763. }
  764. type GitServer interface {
  765. URL() string
  766. Close() error
  767. }
  768. type localGitServer struct {
  769. *httptest.Server
  770. }
  771. func (r *localGitServer) Close() error {
  772. r.Server.Close()
  773. return nil
  774. }
  775. func (r *localGitServer) URL() string {
  776. return r.Server.URL
  777. }
  778. type FakeGIT struct {
  779. root string
  780. server GitServer
  781. RepoURL string
  782. }
  783. func (g *FakeGIT) Close() {
  784. g.server.Close()
  785. os.RemoveAll(g.root)
  786. }
  787. func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) {
  788. ctx, err := fakeContextWithFiles(files)
  789. if err != nil {
  790. return nil, err
  791. }
  792. defer ctx.Close()
  793. curdir, err := os.Getwd()
  794. if err != nil {
  795. return nil, err
  796. }
  797. defer os.Chdir(curdir)
  798. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  799. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  800. }
  801. err = os.Chdir(ctx.Dir)
  802. if err != nil {
  803. return nil, err
  804. }
  805. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  806. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  807. }
  808. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  809. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  810. }
  811. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  812. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  813. }
  814. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  815. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  816. }
  817. root, err := ioutil.TempDir("", "docker-test-git-repo")
  818. if err != nil {
  819. return nil, err
  820. }
  821. repoPath := filepath.Join(root, name+".git")
  822. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  823. os.RemoveAll(root)
  824. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  825. }
  826. err = os.Chdir(repoPath)
  827. if err != nil {
  828. os.RemoveAll(root)
  829. return nil, err
  830. }
  831. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  832. os.RemoveAll(root)
  833. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  834. }
  835. err = os.Chdir(curdir)
  836. if err != nil {
  837. os.RemoveAll(root)
  838. return nil, err
  839. }
  840. var server GitServer
  841. if !enforceLocalServer {
  842. // use fakeStorage server, which might be local or remote (at test daemon)
  843. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  844. if err != nil {
  845. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  846. }
  847. } else {
  848. // always start a local http server on CLI test machin
  849. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  850. server = &localGitServer{httpServer}
  851. }
  852. return &FakeGIT{
  853. root: root,
  854. server: server,
  855. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  856. }, nil
  857. }
  858. // Write `content` to the file at path `dst`, creating it if necessary,
  859. // as well as any missing directories.
  860. // The file is truncated if it already exists.
  861. // Call t.Fatal() at the first error.
  862. func writeFile(dst, content string, t *testing.T) {
  863. // Create subdirectories if necessary
  864. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  865. t.Fatal(err)
  866. }
  867. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  868. if err != nil {
  869. t.Fatal(err)
  870. }
  871. // Write content (truncate if it exists)
  872. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  873. t.Fatal(err)
  874. }
  875. }
  876. // Return the contents of file at path `src`.
  877. // Call t.Fatal() at the first error (including if the file doesn't exist)
  878. func readFile(src string, t *testing.T) (content string) {
  879. data, err := ioutil.ReadFile(src)
  880. if err != nil {
  881. t.Fatal(err)
  882. }
  883. return string(data)
  884. }
  885. func containerStorageFile(containerId, basename string) string {
  886. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  887. }
  888. // docker commands that use this function must be run with the '-d' switch.
  889. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  890. out, _, err := runCommandWithOutput(cmd)
  891. if err != nil {
  892. return nil, fmt.Errorf("%v: %q", err, out)
  893. }
  894. time.Sleep(1 * time.Second)
  895. contID := strings.TrimSpace(out)
  896. return readContainerFile(contID, filename)
  897. }
  898. func readContainerFile(containerId, filename string) ([]byte, error) {
  899. f, err := os.Open(containerStorageFile(containerId, filename))
  900. if err != nil {
  901. return nil, err
  902. }
  903. defer f.Close()
  904. content, err := ioutil.ReadAll(f)
  905. if err != nil {
  906. return nil, err
  907. }
  908. return content, nil
  909. }
  910. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  911. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  912. return []byte(out), err
  913. }
  914. // daemonTime provides the current time on the daemon host
  915. func daemonTime(t *testing.T) time.Time {
  916. if isLocalDaemon {
  917. return time.Now()
  918. }
  919. _, body, err := sockRequest("GET", "/info", nil)
  920. if err != nil {
  921. t.Fatalf("daemonTime: failed to get /info: %v", err)
  922. }
  923. type infoJSON struct {
  924. SystemTime string
  925. }
  926. var info infoJSON
  927. if err = json.Unmarshal(body, &info); err != nil {
  928. t.Fatalf("unable to unmarshal /info response: %v", err)
  929. }
  930. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  931. if err != nil {
  932. t.Fatal(err)
  933. }
  934. return dt
  935. }
  936. func setupRegistry(t *testing.T) func() {
  937. testRequires(t, RegistryHosting)
  938. reg, err := newTestRegistryV2(t)
  939. if err != nil {
  940. t.Fatal(err)
  941. }
  942. // Wait for registry to be ready to serve requests.
  943. for i := 0; i != 5; i++ {
  944. if err = reg.Ping(); err == nil {
  945. break
  946. }
  947. time.Sleep(100 * time.Millisecond)
  948. }
  949. if err != nil {
  950. t.Fatal("Timeout waiting for test registry to become available")
  951. }
  952. return func() { reg.Close() }
  953. }
  954. // appendBaseEnv appends the minimum set of environment variables to exec the
  955. // docker cli binary for testing with correct configuration to the given env
  956. // list.
  957. func appendBaseEnv(env []string) []string {
  958. preserveList := []string{
  959. // preserve remote test host
  960. "DOCKER_HOST",
  961. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  962. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  963. "SystemRoot",
  964. }
  965. for _, key := range preserveList {
  966. if val := os.Getenv(key); val != "" {
  967. env = append(env, fmt.Sprintf("%s=%s", key, val))
  968. }
  969. }
  970. return env
  971. }