docker_utils.go 34 KB

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