docker_utils.go 34 KB

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