docker_utils.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  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" || n.Name == "none" || n.Name == "host" {
  530. continue
  531. }
  532. status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
  533. if err != nil {
  534. errors = append(errors, err.Error())
  535. continue
  536. }
  537. if status != http.StatusNoContent {
  538. errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  539. }
  540. }
  541. if len(errors) > 0 {
  542. return fmt.Errorf(strings.Join(errors, "\n"))
  543. }
  544. return nil
  545. }
  546. func getAllNetworks() ([]types.NetworkResource, error) {
  547. var networks []types.NetworkResource
  548. _, b, err := sockRequest("GET", "/networks", nil)
  549. if err != nil {
  550. return nil, err
  551. }
  552. if err := json.Unmarshal(b, &networks); err != nil {
  553. return nil, err
  554. }
  555. return networks, nil
  556. }
  557. func deleteAllVolumes() error {
  558. volumes, err := getAllVolumes()
  559. if err != nil {
  560. return err
  561. }
  562. var errors []string
  563. for _, v := range volumes {
  564. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
  565. if err != nil {
  566. errors = append(errors, err.Error())
  567. continue
  568. }
  569. if status != http.StatusNoContent {
  570. errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  571. }
  572. }
  573. if len(errors) > 0 {
  574. return fmt.Errorf(strings.Join(errors, "\n"))
  575. }
  576. return nil
  577. }
  578. func getAllVolumes() ([]*types.Volume, error) {
  579. var volumes types.VolumesListResponse
  580. _, b, err := sockRequest("GET", "/volumes", nil)
  581. if err != nil {
  582. return nil, err
  583. }
  584. if err := json.Unmarshal(b, &volumes); err != nil {
  585. return nil, err
  586. }
  587. return volumes.Volumes, nil
  588. }
  589. var protectedImages = map[string]struct{}{}
  590. func deleteAllImages() error {
  591. out, err := exec.Command(dockerBinary, "images").CombinedOutput()
  592. if err != nil {
  593. return err
  594. }
  595. lines := strings.Split(string(out), "\n")[1:]
  596. var imgs []string
  597. for _, l := range lines {
  598. if l == "" {
  599. continue
  600. }
  601. fields := strings.Fields(l)
  602. imgTag := fields[0] + ":" + fields[1]
  603. if _, ok := protectedImages[imgTag]; !ok {
  604. if fields[0] == "<none>" {
  605. imgs = append(imgs, fields[2])
  606. continue
  607. }
  608. imgs = append(imgs, imgTag)
  609. }
  610. }
  611. if len(imgs) == 0 {
  612. return nil
  613. }
  614. args := append([]string{"rmi", "-f"}, imgs...)
  615. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  616. return err
  617. }
  618. return nil
  619. }
  620. func getPausedContainers() (string, error) {
  621. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  622. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  623. if exitCode != 0 && err == nil {
  624. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  625. }
  626. return out, err
  627. }
  628. func getSliceOfPausedContainers() ([]string, error) {
  629. out, err := getPausedContainers()
  630. if err == nil {
  631. if len(out) == 0 {
  632. return nil, err
  633. }
  634. slice := strings.Split(strings.TrimSpace(out), "\n")
  635. return slice, err
  636. }
  637. return []string{out}, err
  638. }
  639. func unpauseContainer(container string) error {
  640. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  641. exitCode, err := runCommand(unpauseCmd)
  642. if exitCode != 0 && err == nil {
  643. err = fmt.Errorf("failed to unpause container")
  644. }
  645. return nil
  646. }
  647. func unpauseAllContainers() error {
  648. containers, err := getPausedContainers()
  649. if err != nil {
  650. fmt.Println(containers)
  651. return err
  652. }
  653. containers = strings.Replace(containers, "\n", " ", -1)
  654. containers = strings.Trim(containers, " ")
  655. containerList := strings.Split(containers, " ")
  656. for _, value := range containerList {
  657. if err = unpauseContainer(value); err != nil {
  658. return err
  659. }
  660. }
  661. return nil
  662. }
  663. func deleteImages(images ...string) error {
  664. args := []string{"rmi", "-f"}
  665. args = append(args, images...)
  666. rmiCmd := exec.Command(dockerBinary, args...)
  667. exitCode, err := runCommand(rmiCmd)
  668. // set error manually if not set
  669. if exitCode != 0 && err == nil {
  670. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  671. }
  672. return err
  673. }
  674. func imageExists(image string) error {
  675. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  676. exitCode, err := runCommand(inspectCmd)
  677. if exitCode != 0 && err == nil {
  678. err = fmt.Errorf("couldn't find image %q", image)
  679. }
  680. return err
  681. }
  682. func pullImageIfNotExist(image string) error {
  683. if err := imageExists(image); err != nil {
  684. pullCmd := exec.Command(dockerBinary, "pull", image)
  685. _, exitCode, err := runCommandWithOutput(pullCmd)
  686. if err != nil || exitCode != 0 {
  687. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  688. }
  689. }
  690. return nil
  691. }
  692. func dockerCmdWithError(args ...string) (string, int, error) {
  693. return integration.DockerCmdWithError(dockerBinary, args...)
  694. }
  695. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  696. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  697. }
  698. func dockerCmd(c *check.C, args ...string) (string, int) {
  699. return integration.DockerCmd(dockerBinary, c, args...)
  700. }
  701. // execute a docker command with a timeout
  702. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  703. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  704. }
  705. // execute a docker command in a directory
  706. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  707. return integration.DockerCmdInDir(dockerBinary, path, args...)
  708. }
  709. // execute a docker command in a directory with a timeout
  710. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  711. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  712. }
  713. func findContainerIP(c *check.C, id string, network string) string {
  714. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  715. return strings.Trim(out, " \r\n'")
  716. }
  717. func (d *Daemon) findContainerIP(id string) string {
  718. out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id)
  719. if err != nil {
  720. d.c.Log(err)
  721. }
  722. return strings.Trim(out, " \r\n'")
  723. }
  724. func getContainerCount() (int, error) {
  725. const containers = "Containers:"
  726. cmd := exec.Command(dockerBinary, "info")
  727. out, _, err := runCommandWithOutput(cmd)
  728. if err != nil {
  729. return 0, err
  730. }
  731. lines := strings.Split(out, "\n")
  732. for _, line := range lines {
  733. if strings.Contains(line, containers) {
  734. output := strings.TrimSpace(line)
  735. output = strings.TrimLeft(output, containers)
  736. output = strings.Trim(output, " ")
  737. containerCount, err := strconv.Atoi(output)
  738. if err != nil {
  739. return 0, err
  740. }
  741. return containerCount, nil
  742. }
  743. }
  744. return 0, fmt.Errorf("couldn't find the Container count in the output")
  745. }
  746. // FakeContext creates directories that can be used as a build context
  747. type FakeContext struct {
  748. Dir string
  749. }
  750. // Add a file at a path, creating directories where necessary
  751. func (f *FakeContext) Add(file, content string) error {
  752. return f.addFile(file, []byte(content))
  753. }
  754. func (f *FakeContext) addFile(file string, content []byte) error {
  755. filepath := path.Join(f.Dir, file)
  756. dirpath := path.Dir(filepath)
  757. if dirpath != "." {
  758. if err := os.MkdirAll(dirpath, 0755); err != nil {
  759. return err
  760. }
  761. }
  762. return ioutil.WriteFile(filepath, content, 0644)
  763. }
  764. // Delete a file at a path
  765. func (f *FakeContext) Delete(file string) error {
  766. filepath := path.Join(f.Dir, file)
  767. return os.RemoveAll(filepath)
  768. }
  769. // Close deletes the context
  770. func (f *FakeContext) Close() error {
  771. return os.RemoveAll(f.Dir)
  772. }
  773. func fakeContextFromNewTempDir() (*FakeContext, error) {
  774. tmp, err := ioutil.TempDir("", "fake-context")
  775. if err != nil {
  776. return nil, err
  777. }
  778. if err := os.Chmod(tmp, 0755); err != nil {
  779. return nil, err
  780. }
  781. return fakeContextFromDir(tmp), nil
  782. }
  783. func fakeContextFromDir(dir string) *FakeContext {
  784. return &FakeContext{dir}
  785. }
  786. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  787. ctx, err := fakeContextFromNewTempDir()
  788. if err != nil {
  789. return nil, err
  790. }
  791. for file, content := range files {
  792. if err := ctx.Add(file, content); err != nil {
  793. ctx.Close()
  794. return nil, err
  795. }
  796. }
  797. return ctx, nil
  798. }
  799. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  800. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  801. ctx.Close()
  802. return err
  803. }
  804. return nil
  805. }
  806. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  807. ctx, err := fakeContextWithFiles(files)
  808. if err != nil {
  809. return nil, err
  810. }
  811. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  812. return nil, err
  813. }
  814. return ctx, nil
  815. }
  816. // FakeStorage is a static file server. It might be running locally or remotely
  817. // on test host.
  818. type FakeStorage interface {
  819. Close() error
  820. URL() string
  821. CtxDir() string
  822. }
  823. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  824. ctx, err := fakeContextFromNewTempDir()
  825. if err != nil {
  826. return nil, err
  827. }
  828. for name, content := range archives {
  829. if err := ctx.addFile(name, content.Bytes()); err != nil {
  830. return nil, err
  831. }
  832. }
  833. return fakeStorageWithContext(ctx)
  834. }
  835. // fakeStorage returns either a local or remote (at daemon machine) file server
  836. func fakeStorage(files map[string]string) (FakeStorage, error) {
  837. ctx, err := fakeContextWithFiles(files)
  838. if err != nil {
  839. return nil, err
  840. }
  841. return fakeStorageWithContext(ctx)
  842. }
  843. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  844. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  845. if isLocalDaemon {
  846. return newLocalFakeStorage(ctx)
  847. }
  848. return newRemoteFileServer(ctx)
  849. }
  850. // localFileStorage is a file storage on the running machine
  851. type localFileStorage struct {
  852. *FakeContext
  853. *httptest.Server
  854. }
  855. func (s *localFileStorage) URL() string {
  856. return s.Server.URL
  857. }
  858. func (s *localFileStorage) CtxDir() string {
  859. return s.FakeContext.Dir
  860. }
  861. func (s *localFileStorage) Close() error {
  862. defer s.Server.Close()
  863. return s.FakeContext.Close()
  864. }
  865. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  866. handler := http.FileServer(http.Dir(ctx.Dir))
  867. server := httptest.NewServer(handler)
  868. return &localFileStorage{
  869. FakeContext: ctx,
  870. Server: server,
  871. }, nil
  872. }
  873. // remoteFileServer is a containerized static file server started on the remote
  874. // testing machine to be used in URL-accepting docker build functionality.
  875. type remoteFileServer struct {
  876. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  877. container string
  878. image string
  879. ctx *FakeContext
  880. }
  881. func (f *remoteFileServer) URL() string {
  882. u := url.URL{
  883. Scheme: "http",
  884. Host: f.host}
  885. return u.String()
  886. }
  887. func (f *remoteFileServer) CtxDir() string {
  888. return f.ctx.Dir
  889. }
  890. func (f *remoteFileServer) Close() error {
  891. defer func() {
  892. if f.ctx != nil {
  893. f.ctx.Close()
  894. }
  895. if f.image != "" {
  896. deleteImages(f.image)
  897. }
  898. }()
  899. if f.container == "" {
  900. return nil
  901. }
  902. return deleteContainer(f.container)
  903. }
  904. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  905. var (
  906. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  907. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  908. )
  909. // Build the image
  910. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  911. COPY . /static`); err != nil {
  912. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  913. }
  914. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  915. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  916. }
  917. // Start the container
  918. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  919. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  920. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  921. }
  922. // Find out the system assigned port
  923. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  924. if err != nil {
  925. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  926. }
  927. fileserverHostPort := strings.Trim(out, "\n")
  928. _, port, err := net.SplitHostPort(fileserverHostPort)
  929. if err != nil {
  930. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  931. }
  932. dockerHostURL, err := url.Parse(daemonHost())
  933. if err != nil {
  934. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  935. }
  936. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  937. if err != nil {
  938. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  939. }
  940. return &remoteFileServer{
  941. container: container,
  942. image: image,
  943. host: fmt.Sprintf("%s:%s", host, port),
  944. ctx: ctx}, nil
  945. }
  946. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  947. str, err := inspectFieldJSON(name, field)
  948. if err != nil {
  949. return err
  950. }
  951. return json.Unmarshal([]byte(str), output)
  952. }
  953. func inspectFilter(name, filter string) (string, error) {
  954. format := fmt.Sprintf("{{%s}}", filter)
  955. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  956. out, exitCode, err := runCommandWithOutput(inspectCmd)
  957. if err != nil || exitCode != 0 {
  958. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  959. }
  960. return strings.TrimSpace(out), nil
  961. }
  962. func inspectField(name, field string) (string, error) {
  963. return inspectFilter(name, fmt.Sprintf(".%s", field))
  964. }
  965. func inspectFieldJSON(name, field string) (string, error) {
  966. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  967. }
  968. func inspectFieldMap(name, path, field string) (string, error) {
  969. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  970. }
  971. func inspectMountSourceField(name, destination string) (string, error) {
  972. m, err := inspectMountPoint(name, destination)
  973. if err != nil {
  974. return "", err
  975. }
  976. return m.Source, nil
  977. }
  978. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  979. out, err := inspectFieldJSON(name, "Mounts")
  980. if err != nil {
  981. return types.MountPoint{}, err
  982. }
  983. return inspectMountPointJSON(out, destination)
  984. }
  985. var errMountNotFound = errors.New("mount point not found")
  986. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  987. var mp []types.MountPoint
  988. if err := unmarshalJSON([]byte(j), &mp); err != nil {
  989. return types.MountPoint{}, err
  990. }
  991. var m *types.MountPoint
  992. for _, c := range mp {
  993. if c.Destination == destination {
  994. m = &c
  995. break
  996. }
  997. }
  998. if m == nil {
  999. return types.MountPoint{}, errMountNotFound
  1000. }
  1001. return *m, nil
  1002. }
  1003. func getIDByName(name string) (string, error) {
  1004. return inspectField(name, "Id")
  1005. }
  1006. // getContainerState returns the exit code of the container
  1007. // and true if it's running
  1008. // the exit code should be ignored if it's running
  1009. func getContainerState(c *check.C, id string) (int, bool, error) {
  1010. var (
  1011. exitStatus int
  1012. running bool
  1013. )
  1014. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  1015. if exitCode != 0 {
  1016. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  1017. }
  1018. out = strings.Trim(out, "\n")
  1019. splitOutput := strings.Split(out, " ")
  1020. if len(splitOutput) != 2 {
  1021. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  1022. }
  1023. if splitOutput[0] == "true" {
  1024. running = true
  1025. }
  1026. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  1027. exitStatus = n
  1028. } else {
  1029. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  1030. }
  1031. return exitStatus, running, nil
  1032. }
  1033. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  1034. args := []string{"-D", "build", "-t", name}
  1035. if !useCache {
  1036. args = append(args, "--no-cache")
  1037. }
  1038. args = append(args, buildFlags...)
  1039. args = append(args, "-")
  1040. buildCmd := exec.Command(dockerBinary, args...)
  1041. buildCmd.Stdin = strings.NewReader(dockerfile)
  1042. return buildCmd
  1043. }
  1044. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  1045. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1046. out, exitCode, err := runCommandWithOutput(buildCmd)
  1047. if err != nil || exitCode != 0 {
  1048. return "", out, fmt.Errorf("failed to build the image: %s", out)
  1049. }
  1050. id, err := getIDByName(name)
  1051. if err != nil {
  1052. return "", out, err
  1053. }
  1054. return id, out, nil
  1055. }
  1056. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  1057. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1058. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1059. if err != nil || exitCode != 0 {
  1060. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1061. }
  1062. id, err := getIDByName(name)
  1063. if err != nil {
  1064. return "", stdout, stderr, err
  1065. }
  1066. return id, stdout, stderr, nil
  1067. }
  1068. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1069. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1070. return id, err
  1071. }
  1072. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1073. args := []string{"build", "-t", name}
  1074. if !useCache {
  1075. args = append(args, "--no-cache")
  1076. }
  1077. args = append(args, buildFlags...)
  1078. args = append(args, ".")
  1079. buildCmd := exec.Command(dockerBinary, args...)
  1080. buildCmd.Dir = ctx.Dir
  1081. out, exitCode, err := runCommandWithOutput(buildCmd)
  1082. if err != nil || exitCode != 0 {
  1083. return "", fmt.Errorf("failed to build the image: %s", out)
  1084. }
  1085. return getIDByName(name)
  1086. }
  1087. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1088. args := []string{"build", "-t", name}
  1089. if !useCache {
  1090. args = append(args, "--no-cache")
  1091. }
  1092. args = append(args, buildFlags...)
  1093. args = append(args, path)
  1094. buildCmd := exec.Command(dockerBinary, args...)
  1095. out, exitCode, err := runCommandWithOutput(buildCmd)
  1096. if err != nil || exitCode != 0 {
  1097. return "", fmt.Errorf("failed to build the image: %s", out)
  1098. }
  1099. return getIDByName(name)
  1100. }
  1101. type gitServer interface {
  1102. URL() string
  1103. Close() error
  1104. }
  1105. type localGitServer struct {
  1106. *httptest.Server
  1107. }
  1108. func (r *localGitServer) Close() error {
  1109. r.Server.Close()
  1110. return nil
  1111. }
  1112. func (r *localGitServer) URL() string {
  1113. return r.Server.URL
  1114. }
  1115. type fakeGit struct {
  1116. root string
  1117. server gitServer
  1118. RepoURL string
  1119. }
  1120. func (g *fakeGit) Close() {
  1121. g.server.Close()
  1122. os.RemoveAll(g.root)
  1123. }
  1124. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1125. ctx, err := fakeContextWithFiles(files)
  1126. if err != nil {
  1127. return nil, err
  1128. }
  1129. defer ctx.Close()
  1130. curdir, err := os.Getwd()
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. defer os.Chdir(curdir)
  1135. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1136. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1137. }
  1138. err = os.Chdir(ctx.Dir)
  1139. if err != nil {
  1140. return nil, err
  1141. }
  1142. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1143. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1144. }
  1145. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1146. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1147. }
  1148. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1149. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1150. }
  1151. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1152. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1153. }
  1154. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1155. if err != nil {
  1156. return nil, err
  1157. }
  1158. repoPath := filepath.Join(root, name+".git")
  1159. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1160. os.RemoveAll(root)
  1161. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1162. }
  1163. err = os.Chdir(repoPath)
  1164. if err != nil {
  1165. os.RemoveAll(root)
  1166. return nil, err
  1167. }
  1168. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1169. os.RemoveAll(root)
  1170. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1171. }
  1172. err = os.Chdir(curdir)
  1173. if err != nil {
  1174. os.RemoveAll(root)
  1175. return nil, err
  1176. }
  1177. var server gitServer
  1178. if !enforceLocalServer {
  1179. // use fakeStorage server, which might be local or remote (at test daemon)
  1180. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1181. if err != nil {
  1182. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1183. }
  1184. } else {
  1185. // always start a local http server on CLI test machin
  1186. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1187. server = &localGitServer{httpServer}
  1188. }
  1189. return &fakeGit{
  1190. root: root,
  1191. server: server,
  1192. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1193. }, nil
  1194. }
  1195. // Write `content` to the file at path `dst`, creating it if necessary,
  1196. // as well as any missing directories.
  1197. // The file is truncated if it already exists.
  1198. // Fail the test when error occures.
  1199. func writeFile(dst, content string, c *check.C) {
  1200. // Create subdirectories if necessary
  1201. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1202. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1203. c.Assert(err, check.IsNil)
  1204. defer f.Close()
  1205. // Write content (truncate if it exists)
  1206. _, err = io.Copy(f, strings.NewReader(content))
  1207. c.Assert(err, check.IsNil)
  1208. }
  1209. // Return the contents of file at path `src`.
  1210. // Fail the test when error occures.
  1211. func readFile(src string, c *check.C) (content string) {
  1212. data, err := ioutil.ReadFile(src)
  1213. c.Assert(err, check.IsNil)
  1214. return string(data)
  1215. }
  1216. func containerStorageFile(containerID, basename string) string {
  1217. return filepath.Join(containerStoragePath, containerID, basename)
  1218. }
  1219. // docker commands that use this function must be run with the '-d' switch.
  1220. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1221. out, _, err := runCommandWithOutput(cmd)
  1222. if err != nil {
  1223. return nil, fmt.Errorf("%v: %q", err, out)
  1224. }
  1225. contID := strings.TrimSpace(out)
  1226. if err := waitRun(contID); err != nil {
  1227. return nil, fmt.Errorf("%v: %q", contID, err)
  1228. }
  1229. return readContainerFile(contID, filename)
  1230. }
  1231. func readContainerFile(containerID, filename string) ([]byte, error) {
  1232. f, err := os.Open(containerStorageFile(containerID, filename))
  1233. if err != nil {
  1234. return nil, err
  1235. }
  1236. defer f.Close()
  1237. content, err := ioutil.ReadAll(f)
  1238. if err != nil {
  1239. return nil, err
  1240. }
  1241. return content, nil
  1242. }
  1243. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1244. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1245. return []byte(out), err
  1246. }
  1247. // daemonTime provides the current time on the daemon host
  1248. func daemonTime(c *check.C) time.Time {
  1249. if isLocalDaemon {
  1250. return time.Now()
  1251. }
  1252. status, body, err := sockRequest("GET", "/info", nil)
  1253. c.Assert(err, check.IsNil)
  1254. c.Assert(status, check.Equals, http.StatusOK)
  1255. type infoJSON struct {
  1256. SystemTime string
  1257. }
  1258. var info infoJSON
  1259. err = json.Unmarshal(body, &info)
  1260. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1261. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1262. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1263. return dt
  1264. }
  1265. func setupRegistry(c *check.C) *testRegistryV2 {
  1266. testRequires(c, RegistryHosting)
  1267. reg, err := newTestRegistryV2(c)
  1268. c.Assert(err, check.IsNil)
  1269. // Wait for registry to be ready to serve requests.
  1270. for i := 0; i != 5; i++ {
  1271. if err = reg.Ping(); err == nil {
  1272. break
  1273. }
  1274. time.Sleep(100 * time.Millisecond)
  1275. }
  1276. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available"))
  1277. return reg
  1278. }
  1279. func setupNotary(c *check.C) *testNotary {
  1280. testRequires(c, NotaryHosting)
  1281. ts, err := newTestNotary(c)
  1282. c.Assert(err, check.IsNil)
  1283. return ts
  1284. }
  1285. // appendBaseEnv appends the minimum set of environment variables to exec the
  1286. // docker cli binary for testing with correct configuration to the given env
  1287. // list.
  1288. func appendBaseEnv(env []string) []string {
  1289. preserveList := []string{
  1290. // preserve remote test host
  1291. "DOCKER_HOST",
  1292. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1293. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1294. "SystemRoot",
  1295. }
  1296. for _, key := range preserveList {
  1297. if val := os.Getenv(key); val != "" {
  1298. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1299. }
  1300. }
  1301. return env
  1302. }
  1303. func createTmpFile(c *check.C, content string) string {
  1304. f, err := ioutil.TempFile("", "testfile")
  1305. c.Assert(err, check.IsNil)
  1306. filename := f.Name()
  1307. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1308. c.Assert(err, check.IsNil)
  1309. return filename
  1310. }
  1311. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1312. args := []string{"--host", socket}
  1313. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1314. out, exitCode, err := runCommandWithOutput(buildCmd)
  1315. if err != nil || exitCode != 0 {
  1316. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1317. }
  1318. return out, nil
  1319. }
  1320. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1321. args = append(args, []string{"-D", "build", "-t", name}...)
  1322. if !useCache {
  1323. args = append(args, "--no-cache")
  1324. }
  1325. args = append(args, "-")
  1326. buildCmd := exec.Command(dockerBinary, args...)
  1327. buildCmd.Stdin = strings.NewReader(dockerfile)
  1328. return buildCmd
  1329. }
  1330. func waitForContainer(contID string, args ...string) error {
  1331. args = append([]string{"run", "--name", contID}, args...)
  1332. cmd := exec.Command(dockerBinary, args...)
  1333. if _, err := runCommand(cmd); err != nil {
  1334. return err
  1335. }
  1336. if err := waitRun(contID); err != nil {
  1337. return err
  1338. }
  1339. return nil
  1340. }
  1341. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1342. func waitRun(contID string) error {
  1343. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1344. }
  1345. // waitExited will wait for the specified container to state exit, subject
  1346. // to a maximum time limit in seconds supplied by the caller
  1347. func waitExited(contID string, duration time.Duration) error {
  1348. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1349. }
  1350. // waitInspect will wait for the specified container to have the specified string
  1351. // in the inspect output. It will wait until the specified timeout (in seconds)
  1352. // is reached.
  1353. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1354. after := time.After(timeout)
  1355. for {
  1356. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  1357. out, _, err := runCommandWithOutput(cmd)
  1358. if err != nil {
  1359. if !strings.Contains(out, "No such") {
  1360. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1361. }
  1362. select {
  1363. case <-after:
  1364. return err
  1365. default:
  1366. time.Sleep(10 * time.Millisecond)
  1367. continue
  1368. }
  1369. }
  1370. out = strings.TrimSpace(out)
  1371. if out == expected {
  1372. break
  1373. }
  1374. select {
  1375. case <-after:
  1376. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1377. default:
  1378. }
  1379. time.Sleep(100 * time.Millisecond)
  1380. }
  1381. return nil
  1382. }
  1383. func getInspectBody(c *check.C, version, id string) []byte {
  1384. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1385. status, body, err := sockRequest("GET", endpoint, nil)
  1386. c.Assert(err, check.IsNil)
  1387. c.Assert(status, check.Equals, http.StatusOK)
  1388. return body
  1389. }