docker_utils.go 43 KB

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