docker_utils.go 32 KB

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