docker_utils.go 31 KB

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