docker_utils.go 44 KB

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