docker_utils.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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 (d *Daemon) LogfileName() string {
  236. return d.logFile.Name()
  237. }
  238. func daemonHost() string {
  239. daemonUrlStr := "unix://" + api.DEFAULTUNIXSOCKET
  240. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  241. daemonUrlStr = daemonHostVar
  242. }
  243. return daemonUrlStr
  244. }
  245. func sockConn(timeout time.Duration) (net.Conn, error) {
  246. daemon := daemonHost()
  247. daemonUrl, err := url.Parse(daemon)
  248. if err != nil {
  249. return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
  250. }
  251. var c net.Conn
  252. switch daemonUrl.Scheme {
  253. case "unix":
  254. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Path, timeout)
  255. case "tcp":
  256. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Host, timeout)
  257. default:
  258. return c, fmt.Errorf("unknown scheme %v (%s)", daemonUrl.Scheme, daemon)
  259. }
  260. }
  261. func sockRequest(method, endpoint string, data interface{}) ([]byte, error) {
  262. jsonData := bytes.NewBuffer(nil)
  263. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  264. return nil, err
  265. }
  266. return sockRequestRaw(method, endpoint, jsonData, "application/json")
  267. }
  268. func sockRequestRaw(method, endpoint string, data io.Reader, ct string) ([]byte, error) {
  269. c, err := sockConn(time.Duration(10 * time.Second))
  270. if err != nil {
  271. return nil, fmt.Errorf("could not dial docker daemon: %v", err)
  272. }
  273. client := httputil.NewClientConn(c, nil)
  274. defer client.Close()
  275. req, err := http.NewRequest(method, endpoint, data)
  276. if err != nil {
  277. return nil, fmt.Errorf("could not create new request: %v", err)
  278. }
  279. if ct == "" {
  280. ct = "application/json"
  281. }
  282. req.Header.Set("Content-Type", ct)
  283. resp, err := client.Do(req)
  284. if err != nil {
  285. return nil, fmt.Errorf("could not perform request: %v", err)
  286. }
  287. defer resp.Body.Close()
  288. if resp.StatusCode != http.StatusOK {
  289. body, _ := ioutil.ReadAll(resp.Body)
  290. return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
  291. }
  292. return ioutil.ReadAll(resp.Body)
  293. }
  294. func deleteContainer(container string) error {
  295. container = strings.Replace(container, "\n", " ", -1)
  296. container = strings.Trim(container, " ")
  297. killArgs := fmt.Sprintf("kill %v", container)
  298. killSplitArgs := strings.Split(killArgs, " ")
  299. killCmd := exec.Command(dockerBinary, killSplitArgs...)
  300. runCommand(killCmd)
  301. rmArgs := fmt.Sprintf("rm -v %v", container)
  302. rmSplitArgs := strings.Split(rmArgs, " ")
  303. rmCmd := exec.Command(dockerBinary, rmSplitArgs...)
  304. exitCode, err := runCommand(rmCmd)
  305. // set error manually if not set
  306. if exitCode != 0 && err == nil {
  307. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  308. }
  309. return err
  310. }
  311. func getAllContainers() (string, error) {
  312. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  313. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  314. if exitCode != 0 && err == nil {
  315. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  316. }
  317. return out, err
  318. }
  319. func deleteAllContainers() error {
  320. containers, err := getAllContainers()
  321. if err != nil {
  322. fmt.Println(containers)
  323. return err
  324. }
  325. if err = deleteContainer(containers); err != nil {
  326. return err
  327. }
  328. return nil
  329. }
  330. func getPausedContainers() (string, error) {
  331. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  332. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  333. if exitCode != 0 && err == nil {
  334. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  335. }
  336. return out, err
  337. }
  338. func getSliceOfPausedContainers() ([]string, error) {
  339. out, err := getPausedContainers()
  340. if err == nil {
  341. slice := strings.Split(strings.TrimSpace(out), "\n")
  342. return slice, err
  343. }
  344. return []string{out}, err
  345. }
  346. func unpauseContainer(container string) error {
  347. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  348. exitCode, err := runCommand(unpauseCmd)
  349. if exitCode != 0 && err == nil {
  350. err = fmt.Errorf("failed to unpause container")
  351. }
  352. return nil
  353. }
  354. func unpauseAllContainers() error {
  355. containers, err := getPausedContainers()
  356. if err != nil {
  357. fmt.Println(containers)
  358. return err
  359. }
  360. containers = strings.Replace(containers, "\n", " ", -1)
  361. containers = strings.Trim(containers, " ")
  362. containerList := strings.Split(containers, " ")
  363. for _, value := range containerList {
  364. if err = unpauseContainer(value); err != nil {
  365. return err
  366. }
  367. }
  368. return nil
  369. }
  370. func deleteImages(images ...string) error {
  371. args := make([]string, 1, 2)
  372. args[0] = "rmi"
  373. args = append(args, images...)
  374. rmiCmd := exec.Command(dockerBinary, args...)
  375. exitCode, err := runCommand(rmiCmd)
  376. // set error manually if not set
  377. if exitCode != 0 && err == nil {
  378. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  379. }
  380. return err
  381. }
  382. func imageExists(image string) error {
  383. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  384. exitCode, err := runCommand(inspectCmd)
  385. if exitCode != 0 && err == nil {
  386. err = fmt.Errorf("couldn't find image %q", image)
  387. }
  388. return err
  389. }
  390. func pullImageIfNotExist(image string) (err error) {
  391. if err := imageExists(image); err != nil {
  392. pullCmd := exec.Command(dockerBinary, "pull", image)
  393. _, exitCode, err := runCommandWithOutput(pullCmd)
  394. if err != nil || exitCode != 0 {
  395. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  396. }
  397. }
  398. return
  399. }
  400. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  401. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  402. if err != nil {
  403. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  404. }
  405. return out, status, err
  406. }
  407. // execute a docker command with a timeout
  408. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  409. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  410. if err != nil {
  411. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  412. }
  413. return out, status, err
  414. }
  415. // execute a docker command in a directory
  416. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  417. dockerCommand := exec.Command(dockerBinary, args...)
  418. dockerCommand.Dir = path
  419. out, status, err := runCommandWithOutput(dockerCommand)
  420. if err != nil {
  421. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  422. }
  423. return out, status, err
  424. }
  425. // execute a docker command in a directory with a timeout
  426. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  427. dockerCommand := exec.Command(dockerBinary, args...)
  428. dockerCommand.Dir = path
  429. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  430. if err != nil {
  431. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  432. }
  433. return out, status, err
  434. }
  435. func findContainerIP(t *testing.T, id string) string {
  436. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  437. out, _, err := runCommandWithOutput(cmd)
  438. if err != nil {
  439. t.Fatal(err, out)
  440. }
  441. return strings.Trim(out, " \r\n'")
  442. }
  443. func getContainerCount() (int, error) {
  444. const containers = "Containers:"
  445. cmd := exec.Command(dockerBinary, "info")
  446. out, _, err := runCommandWithOutput(cmd)
  447. if err != nil {
  448. return 0, err
  449. }
  450. lines := strings.Split(out, "\n")
  451. for _, line := range lines {
  452. if strings.Contains(line, containers) {
  453. output := stripTrailingCharacters(line)
  454. output = strings.TrimLeft(output, containers)
  455. output = strings.Trim(output, " ")
  456. containerCount, err := strconv.Atoi(output)
  457. if err != nil {
  458. return 0, err
  459. }
  460. return containerCount, nil
  461. }
  462. }
  463. return 0, fmt.Errorf("couldn't find the Container count in the output")
  464. }
  465. type FakeContext struct {
  466. Dir string
  467. }
  468. func (f *FakeContext) Add(file, content string) error {
  469. filepath := path.Join(f.Dir, file)
  470. dirpath := path.Dir(filepath)
  471. if dirpath != "." {
  472. if err := os.MkdirAll(dirpath, 0755); err != nil {
  473. return err
  474. }
  475. }
  476. return ioutil.WriteFile(filepath, []byte(content), 0644)
  477. }
  478. func (f *FakeContext) Delete(file string) error {
  479. filepath := path.Join(f.Dir, file)
  480. return os.RemoveAll(filepath)
  481. }
  482. func (f *FakeContext) Close() error {
  483. return os.RemoveAll(f.Dir)
  484. }
  485. func fakeContextFromDir(dir string) *FakeContext {
  486. return &FakeContext{dir}
  487. }
  488. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  489. tmp, err := ioutil.TempDir("", "fake-context")
  490. if err != nil {
  491. return nil, err
  492. }
  493. if err := os.Chmod(tmp, 0755); err != nil {
  494. return nil, err
  495. }
  496. ctx := fakeContextFromDir(tmp)
  497. for file, content := range files {
  498. if err := ctx.Add(file, content); err != nil {
  499. ctx.Close()
  500. return nil, err
  501. }
  502. }
  503. return ctx, nil
  504. }
  505. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  506. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  507. ctx.Close()
  508. return err
  509. }
  510. return nil
  511. }
  512. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  513. ctx, err := fakeContextWithFiles(files)
  514. if err != nil {
  515. ctx.Close()
  516. return nil, err
  517. }
  518. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  519. return nil, err
  520. }
  521. return ctx, nil
  522. }
  523. // FakeStorage is a static file server. It might be running locally or remotely
  524. // on test host.
  525. type FakeStorage interface {
  526. Close() error
  527. URL() string
  528. CtxDir() string
  529. }
  530. // fakeStorage returns either a local or remote (at daemon machine) file server
  531. func fakeStorage(files map[string]string) (FakeStorage, error) {
  532. ctx, err := fakeContextWithFiles(files)
  533. if err != nil {
  534. return nil, err
  535. }
  536. return fakeStorageWithContext(ctx)
  537. }
  538. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  539. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  540. if isLocalDaemon {
  541. return newLocalFakeStorage(ctx)
  542. }
  543. return newRemoteFileServer(ctx)
  544. }
  545. // localFileStorage is a file storage on the running machine
  546. type localFileStorage struct {
  547. *FakeContext
  548. *httptest.Server
  549. }
  550. func (s *localFileStorage) URL() string {
  551. return s.Server.URL
  552. }
  553. func (s *localFileStorage) CtxDir() string {
  554. return s.FakeContext.Dir
  555. }
  556. func (s *localFileStorage) Close() error {
  557. defer s.Server.Close()
  558. return s.FakeContext.Close()
  559. }
  560. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  561. handler := http.FileServer(http.Dir(ctx.Dir))
  562. server := httptest.NewServer(handler)
  563. return &localFileStorage{
  564. FakeContext: ctx,
  565. Server: server,
  566. }, nil
  567. }
  568. // remoteFileServer is a containerized static file server started on the remote
  569. // testing machine to be used in URL-accepting docker build functionality.
  570. type remoteFileServer struct {
  571. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  572. container string
  573. image string
  574. ctx *FakeContext
  575. }
  576. func (f *remoteFileServer) URL() string {
  577. u := url.URL{
  578. Scheme: "http",
  579. Host: f.host}
  580. return u.String()
  581. }
  582. func (f *remoteFileServer) CtxDir() string {
  583. return f.ctx.Dir
  584. }
  585. func (f *remoteFileServer) Close() error {
  586. defer func() {
  587. if f.ctx != nil {
  588. f.ctx.Close()
  589. }
  590. if f.image != "" {
  591. deleteImages(f.image)
  592. }
  593. }()
  594. if f.container == "" {
  595. return nil
  596. }
  597. return deleteContainer(f.container)
  598. }
  599. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  600. var (
  601. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(makeRandomString(10)))
  602. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(makeRandomString(10)))
  603. )
  604. // Build the image
  605. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  606. COPY . /static`); err != nil {
  607. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  608. }
  609. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  610. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  611. }
  612. // Start the container
  613. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  614. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  615. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  616. }
  617. // Find out the system assigned port
  618. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  619. if err != nil {
  620. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  621. }
  622. return &remoteFileServer{
  623. container: container,
  624. image: image,
  625. host: strings.Trim(out, "\n"),
  626. ctx: ctx}, nil
  627. }
  628. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  629. str, err := inspectFieldJSON(name, field)
  630. if err != nil {
  631. return err
  632. }
  633. return json.Unmarshal([]byte(str), output)
  634. }
  635. func inspectFilter(name, filter string) (string, error) {
  636. format := fmt.Sprintf("{{%s}}", filter)
  637. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  638. out, exitCode, err := runCommandWithOutput(inspectCmd)
  639. if err != nil || exitCode != 0 {
  640. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  641. }
  642. return strings.TrimSpace(out), nil
  643. }
  644. func inspectField(name, field string) (string, error) {
  645. return inspectFilter(name, fmt.Sprintf(".%s", field))
  646. }
  647. func inspectFieldJSON(name, field string) (string, error) {
  648. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  649. }
  650. func inspectFieldMap(name, path, field string) (string, error) {
  651. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  652. }
  653. func getIDByName(name string) (string, error) {
  654. return inspectField(name, "Id")
  655. }
  656. // getContainerState returns the exit code of the container
  657. // and true if it's running
  658. // the exit code should be ignored if it's running
  659. func getContainerState(t *testing.T, id string) (int, bool, error) {
  660. var (
  661. exitStatus int
  662. running bool
  663. )
  664. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  665. if err != nil || exitCode != 0 {
  666. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  667. }
  668. out = strings.Trim(out, "\n")
  669. splitOutput := strings.Split(out, " ")
  670. if len(splitOutput) != 2 {
  671. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  672. }
  673. if splitOutput[0] == "true" {
  674. running = true
  675. }
  676. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  677. exitStatus = n
  678. } else {
  679. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  680. }
  681. return exitStatus, running, nil
  682. }
  683. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  684. args := []string{"build", "-t", name}
  685. if !useCache {
  686. args = append(args, "--no-cache")
  687. }
  688. args = append(args, "-")
  689. buildCmd := exec.Command(dockerBinary, args...)
  690. buildCmd.Stdin = strings.NewReader(dockerfile)
  691. out, exitCode, err := runCommandWithOutput(buildCmd)
  692. if err != nil || exitCode != 0 {
  693. return "", out, fmt.Errorf("failed to build the image: %s", out)
  694. }
  695. id, err := getIDByName(name)
  696. if err != nil {
  697. return "", out, err
  698. }
  699. return id, out, nil
  700. }
  701. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  702. args := []string{"build", "-t", name}
  703. if !useCache {
  704. args = append(args, "--no-cache")
  705. }
  706. args = append(args, "-")
  707. buildCmd := exec.Command(dockerBinary, args...)
  708. buildCmd.Stdin = strings.NewReader(dockerfile)
  709. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  710. if err != nil || exitCode != 0 {
  711. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  712. }
  713. id, err := getIDByName(name)
  714. if err != nil {
  715. return "", stdout, stderr, err
  716. }
  717. return id, stdout, stderr, nil
  718. }
  719. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  720. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  721. return id, err
  722. }
  723. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  724. args := []string{"build", "-t", name}
  725. if !useCache {
  726. args = append(args, "--no-cache")
  727. }
  728. args = append(args, ".")
  729. buildCmd := exec.Command(dockerBinary, args...)
  730. buildCmd.Dir = ctx.Dir
  731. out, exitCode, err := runCommandWithOutput(buildCmd)
  732. if err != nil || exitCode != 0 {
  733. return "", fmt.Errorf("failed to build the image: %s", out)
  734. }
  735. return getIDByName(name)
  736. }
  737. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  738. args := []string{"build", "-t", name}
  739. if !useCache {
  740. args = append(args, "--no-cache")
  741. }
  742. args = append(args, path)
  743. buildCmd := exec.Command(dockerBinary, args...)
  744. out, exitCode, err := runCommandWithOutput(buildCmd)
  745. if err != nil || exitCode != 0 {
  746. return "", fmt.Errorf("failed to build the image: %s", out)
  747. }
  748. return getIDByName(name)
  749. }
  750. type GitServer interface {
  751. URL() string
  752. Close() error
  753. }
  754. type localGitServer struct {
  755. *httptest.Server
  756. }
  757. func (r *localGitServer) Close() error {
  758. r.Server.Close()
  759. return nil
  760. }
  761. func (r *localGitServer) URL() string {
  762. return r.Server.URL
  763. }
  764. type FakeGIT struct {
  765. root string
  766. server GitServer
  767. RepoURL string
  768. }
  769. func (g *FakeGIT) Close() {
  770. g.server.Close()
  771. os.RemoveAll(g.root)
  772. }
  773. func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) {
  774. ctx, err := fakeContextWithFiles(files)
  775. if err != nil {
  776. return nil, err
  777. }
  778. defer ctx.Close()
  779. curdir, err := os.Getwd()
  780. if err != nil {
  781. return nil, err
  782. }
  783. defer os.Chdir(curdir)
  784. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  785. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  786. }
  787. err = os.Chdir(ctx.Dir)
  788. if err != nil {
  789. return nil, err
  790. }
  791. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  792. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  793. }
  794. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  795. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  796. }
  797. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  798. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  799. }
  800. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  801. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  802. }
  803. root, err := ioutil.TempDir("", "docker-test-git-repo")
  804. if err != nil {
  805. return nil, err
  806. }
  807. repoPath := filepath.Join(root, name+".git")
  808. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  809. os.RemoveAll(root)
  810. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  811. }
  812. err = os.Chdir(repoPath)
  813. if err != nil {
  814. os.RemoveAll(root)
  815. return nil, err
  816. }
  817. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  818. os.RemoveAll(root)
  819. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  820. }
  821. err = os.Chdir(curdir)
  822. if err != nil {
  823. os.RemoveAll(root)
  824. return nil, err
  825. }
  826. var server GitServer
  827. if !enforceLocalServer {
  828. // use fakeStorage server, which might be local or remote (at test daemon)
  829. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  830. if err != nil {
  831. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  832. }
  833. } else {
  834. // always start a local http server on CLI test machin
  835. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  836. server = &localGitServer{httpServer}
  837. }
  838. return &FakeGIT{
  839. root: root,
  840. server: server,
  841. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  842. }, nil
  843. }
  844. // Write `content` to the file at path `dst`, creating it if necessary,
  845. // as well as any missing directories.
  846. // The file is truncated if it already exists.
  847. // Call t.Fatal() at the first error.
  848. func writeFile(dst, content string, t *testing.T) {
  849. // Create subdirectories if necessary
  850. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  851. t.Fatal(err)
  852. }
  853. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  854. if err != nil {
  855. t.Fatal(err)
  856. }
  857. // Write content (truncate if it exists)
  858. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  859. t.Fatal(err)
  860. }
  861. }
  862. // Return the contents of file at path `src`.
  863. // Call t.Fatal() at the first error (including if the file doesn't exist)
  864. func readFile(src string, t *testing.T) (content string) {
  865. data, err := ioutil.ReadFile(src)
  866. if err != nil {
  867. t.Fatal(err)
  868. }
  869. return string(data)
  870. }
  871. func containerStorageFile(containerId, basename string) string {
  872. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  873. }
  874. // docker commands that use this function must be run with the '-d' switch.
  875. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  876. out, _, err := runCommandWithOutput(cmd)
  877. if err != nil {
  878. return nil, fmt.Errorf("%v: %q", err, out)
  879. }
  880. time.Sleep(1 * time.Second)
  881. contID := strings.TrimSpace(out)
  882. return readContainerFile(contID, filename)
  883. }
  884. func readContainerFile(containerId, filename string) ([]byte, error) {
  885. f, err := os.Open(containerStorageFile(containerId, filename))
  886. if err != nil {
  887. return nil, err
  888. }
  889. defer f.Close()
  890. content, err := ioutil.ReadAll(f)
  891. if err != nil {
  892. return nil, err
  893. }
  894. return content, nil
  895. }
  896. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  897. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  898. return []byte(out), err
  899. }
  900. // daemonTime provides the current time on the daemon host
  901. func daemonTime(t *testing.T) time.Time {
  902. if isLocalDaemon {
  903. return time.Now()
  904. }
  905. body, err := sockRequest("GET", "/info", nil)
  906. if err != nil {
  907. t.Fatal("daemonTime: failed to get /info: %v", err)
  908. }
  909. type infoJSON struct {
  910. SystemTime string
  911. }
  912. var info infoJSON
  913. if err = json.Unmarshal(body, &info); err != nil {
  914. t.Fatalf("unable to unmarshal /info response: %v", err)
  915. }
  916. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  917. if err != nil {
  918. t.Fatal(err)
  919. }
  920. return dt
  921. }
  922. func setupRegistry(t *testing.T) func() {
  923. testRequires(t, RegistryHosting)
  924. reg, err := newTestRegistryV2(t)
  925. if err != nil {
  926. t.Fatal(err)
  927. }
  928. // Wait for registry to be ready to serve requests.
  929. for i := 0; i != 5; i++ {
  930. if err = reg.Ping(); err == nil {
  931. break
  932. }
  933. time.Sleep(100 * time.Millisecond)
  934. }
  935. if err != nil {
  936. t.Fatal("Timeout waiting for test registry to become available")
  937. }
  938. return func() { reg.Close() }
  939. }
  940. // appendBaseEnv appends the minimum set of environment variables to exec the
  941. // docker cli binary for testing with correct configuration to the given env
  942. // list.
  943. func appendBaseEnv(env []string) []string {
  944. preserveList := []string{
  945. // preserve remote test host
  946. "DOCKER_HOST",
  947. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  948. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  949. "SystemRoot",
  950. }
  951. for _, key := range preserveList {
  952. if val := os.Getenv(key); val != "" {
  953. env = append(env, fmt.Sprintf("%s=%s", key, val))
  954. }
  955. }
  956. return env
  957. }