docker_utils.go 33 KB

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