docker_utils.go 29 KB

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