docker_utils.go 35 KB

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