docker_utils.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  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. volumetypes "github.com/docker/docker/api/server/types/volume"
  24. "github.com/docker/docker/api/types"
  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 deleteAllVolumes() error {
  271. volumes, err := getAllVolumes()
  272. if err != nil {
  273. return err
  274. }
  275. var errors []string
  276. for _, v := range volumes {
  277. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, 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 volume %s: %s", v.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 getAllVolumes() ([]*types.Volume, error) {
  292. var volumes volumetypes.VolumesListOKBody
  293. _, b, err := sockRequest("GET", "/volumes", nil)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if err := json.Unmarshal(b, &volumes); err != nil {
  298. return nil, err
  299. }
  300. return volumes.Volumes, nil
  301. }
  302. var protectedImages = map[string]struct{}{}
  303. func deleteAllImages() error {
  304. cmd := exec.Command(dockerBinary, "images")
  305. cmd.Env = appendBaseEnv(true)
  306. out, err := cmd.CombinedOutput()
  307. if err != nil {
  308. return err
  309. }
  310. lines := strings.Split(string(out), "\n")[1:]
  311. var imgs []string
  312. for _, l := range lines {
  313. if l == "" {
  314. continue
  315. }
  316. fields := strings.Fields(l)
  317. imgTag := fields[0] + ":" + fields[1]
  318. if _, ok := protectedImages[imgTag]; !ok {
  319. if fields[0] == "<none>" {
  320. imgs = append(imgs, fields[2])
  321. continue
  322. }
  323. imgs = append(imgs, imgTag)
  324. }
  325. }
  326. if len(imgs) == 0 {
  327. return nil
  328. }
  329. args := append([]string{"rmi", "-f"}, imgs...)
  330. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  331. return err
  332. }
  333. return nil
  334. }
  335. func getPausedContainers() (string, error) {
  336. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  337. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  338. if exitCode != 0 && err == nil {
  339. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  340. }
  341. return out, err
  342. }
  343. func getSliceOfPausedContainers() ([]string, error) {
  344. out, err := getPausedContainers()
  345. if err == nil {
  346. if len(out) == 0 {
  347. return nil, err
  348. }
  349. slice := strings.Split(strings.TrimSpace(out), "\n")
  350. return slice, err
  351. }
  352. return []string{out}, err
  353. }
  354. func unpauseContainer(container string) error {
  355. return icmd.RunCommand(dockerBinary, "unpause", container).Error
  356. }
  357. func unpauseAllContainers() error {
  358. containers, err := getPausedContainers()
  359. if err != nil {
  360. fmt.Println(containers)
  361. return err
  362. }
  363. containers = strings.Replace(containers, "\n", " ", -1)
  364. containers = strings.Trim(containers, " ")
  365. containerList := strings.Split(containers, " ")
  366. for _, value := range containerList {
  367. if err = unpauseContainer(value); err != nil {
  368. return err
  369. }
  370. }
  371. return nil
  372. }
  373. func deleteImages(images ...string) error {
  374. args := []string{dockerBinary, "rmi", "-f"}
  375. return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error
  376. }
  377. func imageExists(image string) error {
  378. return icmd.RunCommand(dockerBinary, "inspect", image).Error
  379. }
  380. func pullImageIfNotExist(image string) error {
  381. if err := imageExists(image); err != nil {
  382. pullCmd := exec.Command(dockerBinary, "pull", image)
  383. _, exitCode, err := runCommandWithOutput(pullCmd)
  384. if err != nil || exitCode != 0 {
  385. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  386. }
  387. }
  388. return nil
  389. }
  390. func dockerCmdWithError(args ...string) (string, int, error) {
  391. if err := validateArgs(args...); err != nil {
  392. return "", 0, err
  393. }
  394. result := icmd.RunCommand(dockerBinary, args...)
  395. if result.Error != nil {
  396. return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
  397. }
  398. return result.Combined(), result.ExitCode, result.Error
  399. }
  400. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  401. if err := validateArgs(args...); err != nil {
  402. c.Fatalf(err.Error())
  403. }
  404. result := icmd.RunCommand(dockerBinary, args...)
  405. // TODO: why is c ever nil?
  406. if c != nil {
  407. c.Assert(result, icmd.Matches, icmd.Success)
  408. }
  409. return result.Stdout(), result.Stderr(), result.ExitCode
  410. }
  411. func dockerCmd(c *check.C, args ...string) (string, int) {
  412. if err := validateArgs(args...); err != nil {
  413. c.Fatalf(err.Error())
  414. }
  415. result := icmd.RunCommand(dockerBinary, args...)
  416. c.Assert(result, icmd.Matches, icmd.Success)
  417. return result.Combined(), result.ExitCode
  418. }
  419. func dockerCmdWithResult(args ...string) *icmd.Result {
  420. return icmd.RunCommand(dockerBinary, args...)
  421. }
  422. func binaryWithArgs(args ...string) []string {
  423. return append([]string{dockerBinary}, args...)
  424. }
  425. // execute a docker command with a timeout
  426. func dockerCmdWithTimeout(timeout time.Duration, args ...string) *icmd.Result {
  427. if err := validateArgs(args...); err != nil {
  428. return &icmd.Result{Error: err}
  429. }
  430. return icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Timeout: timeout})
  431. }
  432. // execute a docker command in a directory
  433. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  434. if err := validateArgs(args...); err != nil {
  435. c.Fatalf(err.Error())
  436. }
  437. result := icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Dir: path})
  438. return result.Combined(), result.ExitCode, result.Error
  439. }
  440. // execute a docker command in a directory with a timeout
  441. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) *icmd.Result {
  442. if err := validateArgs(args...); err != nil {
  443. return &icmd.Result{Error: err}
  444. }
  445. return icmd.RunCmd(icmd.Cmd{
  446. Command: binaryWithArgs(args...),
  447. Timeout: timeout,
  448. Dir: path,
  449. })
  450. }
  451. // validateArgs is a checker to ensure tests are not running commands which are
  452. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  453. func validateArgs(args ...string) error {
  454. if daemonPlatform != "windows" {
  455. return nil
  456. }
  457. foundBusybox := -1
  458. for key, value := range args {
  459. if strings.ToLower(value) == "busybox" {
  460. foundBusybox = key
  461. }
  462. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  463. return errors.New("cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  464. }
  465. }
  466. return nil
  467. }
  468. // find the State.ExitCode in container metadata
  469. func findContainerExitCode(c *check.C, name string, vargs ...string) string {
  470. args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
  471. cmd := exec.Command(dockerBinary, args...)
  472. out, _, err := runCommandWithOutput(cmd)
  473. if err != nil {
  474. c.Fatal(err, out)
  475. }
  476. return out
  477. }
  478. func findContainerIP(c *check.C, id string, network string) string {
  479. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  480. return strings.Trim(out, " \r\n'")
  481. }
  482. func getContainerCount() (int, error) {
  483. const containers = "Containers:"
  484. cmd := exec.Command(dockerBinary, "info")
  485. out, _, err := runCommandWithOutput(cmd)
  486. if err != nil {
  487. return 0, err
  488. }
  489. lines := strings.Split(out, "\n")
  490. for _, line := range lines {
  491. if strings.Contains(line, containers) {
  492. output := strings.TrimSpace(line)
  493. output = strings.TrimLeft(output, containers)
  494. output = strings.Trim(output, " ")
  495. containerCount, err := strconv.Atoi(output)
  496. if err != nil {
  497. return 0, err
  498. }
  499. return containerCount, nil
  500. }
  501. }
  502. return 0, fmt.Errorf("couldn't find the Container count in the output")
  503. }
  504. // FakeContext creates directories that can be used as a build context
  505. type FakeContext struct {
  506. Dir string
  507. }
  508. // Add a file at a path, creating directories where necessary
  509. func (f *FakeContext) Add(file, content string) error {
  510. return f.addFile(file, []byte(content))
  511. }
  512. func (f *FakeContext) addFile(file string, content []byte) error {
  513. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  514. dirpath := filepath.Dir(fp)
  515. if dirpath != "." {
  516. if err := os.MkdirAll(dirpath, 0755); err != nil {
  517. return err
  518. }
  519. }
  520. return ioutil.WriteFile(fp, content, 0644)
  521. }
  522. // Delete a file at a path
  523. func (f *FakeContext) Delete(file string) error {
  524. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  525. return os.RemoveAll(fp)
  526. }
  527. // Close deletes the context
  528. func (f *FakeContext) Close() error {
  529. return os.RemoveAll(f.Dir)
  530. }
  531. func fakeContextFromNewTempDir() (*FakeContext, error) {
  532. tmp, err := ioutil.TempDir("", "fake-context")
  533. if err != nil {
  534. return nil, err
  535. }
  536. if err := os.Chmod(tmp, 0755); err != nil {
  537. return nil, err
  538. }
  539. return fakeContextFromDir(tmp), nil
  540. }
  541. func fakeContextFromDir(dir string) *FakeContext {
  542. return &FakeContext{dir}
  543. }
  544. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  545. ctx, err := fakeContextFromNewTempDir()
  546. if err != nil {
  547. return nil, err
  548. }
  549. for file, content := range files {
  550. if err := ctx.Add(file, content); err != nil {
  551. ctx.Close()
  552. return nil, err
  553. }
  554. }
  555. return ctx, nil
  556. }
  557. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  558. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  559. ctx.Close()
  560. return err
  561. }
  562. return nil
  563. }
  564. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  565. ctx, err := fakeContextWithFiles(files)
  566. if err != nil {
  567. return nil, err
  568. }
  569. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  570. return nil, err
  571. }
  572. return ctx, nil
  573. }
  574. // FakeStorage is a static file server. It might be running locally or remotely
  575. // on test host.
  576. type FakeStorage interface {
  577. Close() error
  578. URL() string
  579. CtxDir() string
  580. }
  581. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  582. ctx, err := fakeContextFromNewTempDir()
  583. if err != nil {
  584. return nil, err
  585. }
  586. for name, content := range archives {
  587. if err := ctx.addFile(name, content.Bytes()); err != nil {
  588. return nil, err
  589. }
  590. }
  591. return fakeStorageWithContext(ctx)
  592. }
  593. // fakeStorage returns either a local or remote (at daemon machine) file server
  594. func fakeStorage(files map[string]string) (FakeStorage, error) {
  595. ctx, err := fakeContextWithFiles(files)
  596. if err != nil {
  597. return nil, err
  598. }
  599. return fakeStorageWithContext(ctx)
  600. }
  601. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  602. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  603. if isLocalDaemon {
  604. return newLocalFakeStorage(ctx)
  605. }
  606. return newRemoteFileServer(ctx)
  607. }
  608. // localFileStorage is a file storage on the running machine
  609. type localFileStorage struct {
  610. *FakeContext
  611. *httptest.Server
  612. }
  613. func (s *localFileStorage) URL() string {
  614. return s.Server.URL
  615. }
  616. func (s *localFileStorage) CtxDir() string {
  617. return s.FakeContext.Dir
  618. }
  619. func (s *localFileStorage) Close() error {
  620. defer s.Server.Close()
  621. return s.FakeContext.Close()
  622. }
  623. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  624. handler := http.FileServer(http.Dir(ctx.Dir))
  625. server := httptest.NewServer(handler)
  626. return &localFileStorage{
  627. FakeContext: ctx,
  628. Server: server,
  629. }, nil
  630. }
  631. // remoteFileServer is a containerized static file server started on the remote
  632. // testing machine to be used in URL-accepting docker build functionality.
  633. type remoteFileServer struct {
  634. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  635. container string
  636. image string
  637. ctx *FakeContext
  638. }
  639. func (f *remoteFileServer) URL() string {
  640. u := url.URL{
  641. Scheme: "http",
  642. Host: f.host}
  643. return u.String()
  644. }
  645. func (f *remoteFileServer) CtxDir() string {
  646. return f.ctx.Dir
  647. }
  648. func (f *remoteFileServer) Close() error {
  649. defer func() {
  650. if f.ctx != nil {
  651. f.ctx.Close()
  652. }
  653. if f.image != "" {
  654. deleteImages(f.image)
  655. }
  656. }()
  657. if f.container == "" {
  658. return nil
  659. }
  660. return deleteContainer(f.container)
  661. }
  662. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  663. var (
  664. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  665. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  666. )
  667. if err := ensureHTTPServerImage(); err != nil {
  668. return nil, err
  669. }
  670. // Build the image
  671. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  672. COPY . /static`); err != nil {
  673. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  674. }
  675. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  676. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  677. }
  678. // Start the container
  679. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  680. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  681. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  682. }
  683. // Find out the system assigned port
  684. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  685. if err != nil {
  686. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  687. }
  688. fileserverHostPort := strings.Trim(out, "\n")
  689. _, port, err := net.SplitHostPort(fileserverHostPort)
  690. if err != nil {
  691. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  692. }
  693. dockerHostURL, err := url.Parse(daemonHost())
  694. if err != nil {
  695. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  696. }
  697. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  698. if err != nil {
  699. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  700. }
  701. return &remoteFileServer{
  702. container: container,
  703. image: image,
  704. host: fmt.Sprintf("%s:%s", host, port),
  705. ctx: ctx}, nil
  706. }
  707. func inspectFieldAndMarshall(c *check.C, name, field string, output interface{}) {
  708. str := inspectFieldJSON(c, name, field)
  709. err := json.Unmarshal([]byte(str), output)
  710. if c != nil {
  711. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  712. }
  713. }
  714. func inspectFilter(name, filter string) (string, error) {
  715. format := fmt.Sprintf("{{%s}}", filter)
  716. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  717. out, exitCode, err := runCommandWithOutput(inspectCmd)
  718. if err != nil || exitCode != 0 {
  719. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  720. }
  721. return strings.TrimSpace(out), nil
  722. }
  723. func inspectFieldWithError(name, field string) (string, error) {
  724. return inspectFilter(name, fmt.Sprintf(".%s", field))
  725. }
  726. func inspectField(c *check.C, name, field string) string {
  727. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  728. if c != nil {
  729. c.Assert(err, check.IsNil)
  730. }
  731. return out
  732. }
  733. func inspectFieldJSON(c *check.C, name, field string) string {
  734. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  735. if c != nil {
  736. c.Assert(err, check.IsNil)
  737. }
  738. return out
  739. }
  740. func inspectFieldMap(c *check.C, name, path, field string) string {
  741. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  742. if c != nil {
  743. c.Assert(err, check.IsNil)
  744. }
  745. return out
  746. }
  747. func inspectMountSourceField(name, destination string) (string, error) {
  748. m, err := inspectMountPoint(name, destination)
  749. if err != nil {
  750. return "", err
  751. }
  752. return m.Source, nil
  753. }
  754. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  755. out, err := inspectFilter(name, "json .Mounts")
  756. if err != nil {
  757. return types.MountPoint{}, err
  758. }
  759. return inspectMountPointJSON(out, destination)
  760. }
  761. var errMountNotFound = errors.New("mount point not found")
  762. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  763. var mp []types.MountPoint
  764. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  765. return types.MountPoint{}, err
  766. }
  767. var m *types.MountPoint
  768. for _, c := range mp {
  769. if c.Destination == destination {
  770. m = &c
  771. break
  772. }
  773. }
  774. if m == nil {
  775. return types.MountPoint{}, errMountNotFound
  776. }
  777. return *m, nil
  778. }
  779. func inspectImage(name, filter string) (string, error) {
  780. args := []string{"inspect", "--type", "image"}
  781. if filter != "" {
  782. format := fmt.Sprintf("{{%s}}", filter)
  783. args = append(args, "-f", format)
  784. }
  785. args = append(args, name)
  786. inspectCmd := exec.Command(dockerBinary, args...)
  787. out, exitCode, err := runCommandWithOutput(inspectCmd)
  788. if err != nil || exitCode != 0 {
  789. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  790. }
  791. return strings.TrimSpace(out), nil
  792. }
  793. func getIDByName(name string) (string, error) {
  794. return inspectFieldWithError(name, "Id")
  795. }
  796. // getContainerState returns the exit code of the container
  797. // and true if it's running
  798. // the exit code should be ignored if it's running
  799. func getContainerState(c *check.C, id string) (int, bool, error) {
  800. var (
  801. exitStatus int
  802. running bool
  803. )
  804. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  805. if exitCode != 0 {
  806. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  807. }
  808. out = strings.Trim(out, "\n")
  809. splitOutput := strings.Split(out, " ")
  810. if len(splitOutput) != 2 {
  811. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  812. }
  813. if splitOutput[0] == "true" {
  814. running = true
  815. }
  816. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  817. exitStatus = n
  818. } else {
  819. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  820. }
  821. return exitStatus, running, nil
  822. }
  823. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  824. return buildImageCmdWithHost(name, dockerfile, "", useCache, buildFlags...)
  825. }
  826. func buildImageCmdWithHost(name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
  827. args := []string{}
  828. if host != "" {
  829. args = append(args, "--host", host)
  830. }
  831. args = append(args, "build", "-t", name)
  832. if !useCache {
  833. args = append(args, "--no-cache")
  834. }
  835. args = append(args, buildFlags...)
  836. args = append(args, "-")
  837. buildCmd := exec.Command(dockerBinary, args...)
  838. buildCmd.Stdin = strings.NewReader(dockerfile)
  839. return buildCmd
  840. }
  841. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  842. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  843. out, exitCode, err := runCommandWithOutput(buildCmd)
  844. if err != nil || exitCode != 0 {
  845. return "", out, fmt.Errorf("failed to build the image: %s", out)
  846. }
  847. id, err := getIDByName(name)
  848. if err != nil {
  849. return "", out, err
  850. }
  851. return id, out, nil
  852. }
  853. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  854. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  855. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  856. if err != nil || exitCode != 0 {
  857. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  858. }
  859. id, err := getIDByName(name)
  860. if err != nil {
  861. return "", stdout, stderr, err
  862. }
  863. return id, stdout, stderr, nil
  864. }
  865. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  866. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  867. return id, err
  868. }
  869. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  870. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  871. if err != nil {
  872. return "", err
  873. }
  874. return id, nil
  875. }
  876. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  877. args := []string{"build", "-t", name}
  878. if !useCache {
  879. args = append(args, "--no-cache")
  880. }
  881. args = append(args, buildFlags...)
  882. args = append(args, ".")
  883. buildCmd := exec.Command(dockerBinary, args...)
  884. buildCmd.Dir = ctx.Dir
  885. out, exitCode, err := runCommandWithOutput(buildCmd)
  886. if err != nil || exitCode != 0 {
  887. return "", "", fmt.Errorf("failed to build the image: %s", out)
  888. }
  889. id, err := getIDByName(name)
  890. if err != nil {
  891. return "", "", err
  892. }
  893. return id, out, nil
  894. }
  895. func buildImageFromContextWithStdoutStderr(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, string, error) {
  896. args := []string{"build", "-t", name}
  897. if !useCache {
  898. args = append(args, "--no-cache")
  899. }
  900. args = append(args, buildFlags...)
  901. args = append(args, ".")
  902. buildCmd := exec.Command(dockerBinary, args...)
  903. buildCmd.Dir = ctx.Dir
  904. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  905. if err != nil || exitCode != 0 {
  906. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  907. }
  908. id, err := getIDByName(name)
  909. if err != nil {
  910. return "", stdout, stderr, err
  911. }
  912. return id, stdout, stderr, nil
  913. }
  914. func buildImageFromGitWithStdoutStderr(name string, ctx *fakeGit, useCache bool, buildFlags ...string) (string, string, string, error) {
  915. args := []string{"build", "-t", name}
  916. if !useCache {
  917. args = append(args, "--no-cache")
  918. }
  919. args = append(args, buildFlags...)
  920. args = append(args, ctx.RepoURL)
  921. buildCmd := exec.Command(dockerBinary, args...)
  922. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  923. if err != nil || exitCode != 0 {
  924. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  925. }
  926. id, err := getIDByName(name)
  927. if err != nil {
  928. return "", stdout, stderr, err
  929. }
  930. return id, stdout, stderr, nil
  931. }
  932. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  933. args := []string{"build", "-t", name}
  934. if !useCache {
  935. args = append(args, "--no-cache")
  936. }
  937. args = append(args, buildFlags...)
  938. args = append(args, path)
  939. buildCmd := exec.Command(dockerBinary, args...)
  940. out, exitCode, err := runCommandWithOutput(buildCmd)
  941. if err != nil || exitCode != 0 {
  942. return "", fmt.Errorf("failed to build the image: %s", out)
  943. }
  944. return getIDByName(name)
  945. }
  946. type gitServer interface {
  947. URL() string
  948. Close() error
  949. }
  950. type localGitServer struct {
  951. *httptest.Server
  952. }
  953. func (r *localGitServer) Close() error {
  954. r.Server.Close()
  955. return nil
  956. }
  957. func (r *localGitServer) URL() string {
  958. return r.Server.URL
  959. }
  960. type fakeGit struct {
  961. root string
  962. server gitServer
  963. RepoURL string
  964. }
  965. func (g *fakeGit) Close() {
  966. g.server.Close()
  967. os.RemoveAll(g.root)
  968. }
  969. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  970. ctx, err := fakeContextWithFiles(files)
  971. if err != nil {
  972. return nil, err
  973. }
  974. defer ctx.Close()
  975. curdir, err := os.Getwd()
  976. if err != nil {
  977. return nil, err
  978. }
  979. defer os.Chdir(curdir)
  980. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  981. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  982. }
  983. err = os.Chdir(ctx.Dir)
  984. if err != nil {
  985. return nil, err
  986. }
  987. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  988. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  989. }
  990. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  991. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  992. }
  993. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  994. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  995. }
  996. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  997. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  998. }
  999. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1000. if err != nil {
  1001. return nil, err
  1002. }
  1003. repoPath := filepath.Join(root, name+".git")
  1004. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1005. os.RemoveAll(root)
  1006. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1007. }
  1008. err = os.Chdir(repoPath)
  1009. if err != nil {
  1010. os.RemoveAll(root)
  1011. return nil, err
  1012. }
  1013. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1014. os.RemoveAll(root)
  1015. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1016. }
  1017. err = os.Chdir(curdir)
  1018. if err != nil {
  1019. os.RemoveAll(root)
  1020. return nil, err
  1021. }
  1022. var server gitServer
  1023. if !enforceLocalServer {
  1024. // use fakeStorage server, which might be local or remote (at test daemon)
  1025. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1026. if err != nil {
  1027. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1028. }
  1029. } else {
  1030. // always start a local http server on CLI test machine
  1031. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1032. server = &localGitServer{httpServer}
  1033. }
  1034. return &fakeGit{
  1035. root: root,
  1036. server: server,
  1037. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1038. }, nil
  1039. }
  1040. // Write `content` to the file at path `dst`, creating it if necessary,
  1041. // as well as any missing directories.
  1042. // The file is truncated if it already exists.
  1043. // Fail the test when error occurs.
  1044. func writeFile(dst, content string, c *check.C) {
  1045. // Create subdirectories if necessary
  1046. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1047. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1048. c.Assert(err, check.IsNil)
  1049. defer f.Close()
  1050. // Write content (truncate if it exists)
  1051. _, err = io.Copy(f, strings.NewReader(content))
  1052. c.Assert(err, check.IsNil)
  1053. }
  1054. // Return the contents of file at path `src`.
  1055. // Fail the test when error occurs.
  1056. func readFile(src string, c *check.C) (content string) {
  1057. data, err := ioutil.ReadFile(src)
  1058. c.Assert(err, check.IsNil)
  1059. return string(data)
  1060. }
  1061. func containerStorageFile(containerID, basename string) string {
  1062. return filepath.Join(containerStoragePath, containerID, basename)
  1063. }
  1064. // docker commands that use this function must be run with the '-d' switch.
  1065. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1066. out, _, err := runCommandWithOutput(cmd)
  1067. if err != nil {
  1068. return nil, fmt.Errorf("%v: %q", err, out)
  1069. }
  1070. contID := strings.TrimSpace(out)
  1071. if err := waitRun(contID); err != nil {
  1072. return nil, fmt.Errorf("%v: %q", contID, err)
  1073. }
  1074. return readContainerFile(contID, filename)
  1075. }
  1076. func readContainerFile(containerID, filename string) ([]byte, error) {
  1077. f, err := os.Open(containerStorageFile(containerID, filename))
  1078. if err != nil {
  1079. return nil, err
  1080. }
  1081. defer f.Close()
  1082. content, err := ioutil.ReadAll(f)
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. return content, nil
  1087. }
  1088. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1089. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1090. return []byte(out), err
  1091. }
  1092. // daemonTime provides the current time on the daemon host
  1093. func daemonTime(c *check.C) time.Time {
  1094. if isLocalDaemon {
  1095. return time.Now()
  1096. }
  1097. status, body, err := sockRequest("GET", "/info", nil)
  1098. c.Assert(err, check.IsNil)
  1099. c.Assert(status, check.Equals, http.StatusOK)
  1100. type infoJSON struct {
  1101. SystemTime string
  1102. }
  1103. var info infoJSON
  1104. err = json.Unmarshal(body, &info)
  1105. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1106. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1107. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1108. return dt
  1109. }
  1110. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  1111. // It return the time formatted how the client sends timestamps to the server.
  1112. func daemonUnixTime(c *check.C) string {
  1113. return parseEventTime(daemonTime(c))
  1114. }
  1115. func parseEventTime(t time.Time) string {
  1116. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  1117. }
  1118. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *testRegistryV2 {
  1119. reg, err := newTestRegistryV2(c, schema1, auth, tokenURL)
  1120. c.Assert(err, check.IsNil)
  1121. // Wait for registry to be ready to serve requests.
  1122. for i := 0; i != 50; i++ {
  1123. if err = reg.Ping(); err == nil {
  1124. break
  1125. }
  1126. time.Sleep(100 * time.Millisecond)
  1127. }
  1128. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  1129. return reg
  1130. }
  1131. func setupNotary(c *check.C) *testNotary {
  1132. ts, err := newTestNotary(c)
  1133. c.Assert(err, check.IsNil)
  1134. return ts
  1135. }
  1136. // appendBaseEnv appends the minimum set of environment variables to exec the
  1137. // docker cli binary for testing with correct configuration to the given env
  1138. // list.
  1139. func appendBaseEnv(isTLS bool, env ...string) []string {
  1140. preserveList := []string{
  1141. // preserve remote test host
  1142. "DOCKER_HOST",
  1143. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1144. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1145. "SystemRoot",
  1146. // testing help text requires the $PATH to dockerd is set
  1147. "PATH",
  1148. }
  1149. if isTLS {
  1150. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  1151. }
  1152. for _, key := range preserveList {
  1153. if val := os.Getenv(key); val != "" {
  1154. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1155. }
  1156. }
  1157. return env
  1158. }
  1159. func createTmpFile(c *check.C, content string) string {
  1160. f, err := ioutil.TempFile("", "testfile")
  1161. c.Assert(err, check.IsNil)
  1162. filename := f.Name()
  1163. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1164. c.Assert(err, check.IsNil)
  1165. return filename
  1166. }
  1167. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1168. args := []string{"--host", socket}
  1169. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1170. out, exitCode, err := runCommandWithOutput(buildCmd)
  1171. if err != nil || exitCode != 0 {
  1172. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1173. }
  1174. return out, nil
  1175. }
  1176. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1177. args = append(args, []string{"-D", "build", "-t", name}...)
  1178. if !useCache {
  1179. args = append(args, "--no-cache")
  1180. }
  1181. args = append(args, "-")
  1182. buildCmd := exec.Command(dockerBinary, args...)
  1183. buildCmd.Stdin = strings.NewReader(dockerfile)
  1184. return buildCmd
  1185. }
  1186. func waitForContainer(contID string, args ...string) error {
  1187. args = append([]string{dockerBinary, "run", "--name", contID}, args...)
  1188. result := icmd.RunCmd(icmd.Cmd{Command: args})
  1189. if result.Error != nil {
  1190. return result.Error
  1191. }
  1192. return waitRun(contID)
  1193. }
  1194. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1195. func waitRun(contID string) error {
  1196. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1197. }
  1198. // waitExited will wait for the specified container to state exit, subject
  1199. // to a maximum time limit in seconds supplied by the caller
  1200. func waitExited(contID string, duration time.Duration) error {
  1201. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1202. }
  1203. // waitInspect will wait for the specified container to have the specified string
  1204. // in the inspect output. It will wait until the specified timeout (in seconds)
  1205. // is reached.
  1206. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1207. return waitInspectWithArgs(name, expr, expected, timeout)
  1208. }
  1209. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1210. after := time.After(timeout)
  1211. args := append(arg, "inspect", "-f", expr, name)
  1212. for {
  1213. result := icmd.RunCommand(dockerBinary, args...)
  1214. if result.Error != nil {
  1215. if !strings.Contains(result.Stderr(), "No such") {
  1216. return fmt.Errorf("error executing docker inspect: %v\n%s",
  1217. result.Stderr(), result.Stdout())
  1218. }
  1219. select {
  1220. case <-after:
  1221. return result.Error
  1222. default:
  1223. time.Sleep(10 * time.Millisecond)
  1224. continue
  1225. }
  1226. }
  1227. out := strings.TrimSpace(result.Stdout())
  1228. if out == expected {
  1229. break
  1230. }
  1231. select {
  1232. case <-after:
  1233. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1234. default:
  1235. }
  1236. time.Sleep(100 * time.Millisecond)
  1237. }
  1238. return nil
  1239. }
  1240. func getInspectBody(c *check.C, version, id string) []byte {
  1241. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1242. status, body, err := sockRequest("GET", endpoint, nil)
  1243. c.Assert(err, check.IsNil)
  1244. c.Assert(status, check.Equals, http.StatusOK)
  1245. return body
  1246. }
  1247. // Run a long running idle task in a background container using the
  1248. // system-specific default image and command.
  1249. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1250. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1251. }
  1252. // Run a long running idle task in a background container using the specified
  1253. // image and the system-specific command.
  1254. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1255. args := []string{"run", "-d"}
  1256. args = append(args, extraArgs...)
  1257. args = append(args, image)
  1258. args = append(args, sleepCommandForDaemonPlatform()...)
  1259. return dockerCmd(c, args...)
  1260. }
  1261. func getRootUIDGID() (int, int, error) {
  1262. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1263. if len(uidgid) == 1 {
  1264. //user namespace remapping is not turned on; return 0
  1265. return 0, 0, nil
  1266. }
  1267. uid, err := strconv.Atoi(uidgid[0])
  1268. if err != nil {
  1269. return 0, 0, err
  1270. }
  1271. gid, err := strconv.Atoi(uidgid[1])
  1272. if err != nil {
  1273. return 0, 0, err
  1274. }
  1275. return uid, gid, nil
  1276. }
  1277. // minimalBaseImage returns the name of the minimal base image for the current
  1278. // daemon platform.
  1279. func minimalBaseImage() string {
  1280. if daemonPlatform == "windows" {
  1281. return WindowsBaseImage
  1282. }
  1283. return "scratch"
  1284. }
  1285. func getGoroutineNumber() (int, error) {
  1286. i := struct {
  1287. NGoroutines int
  1288. }{}
  1289. status, b, err := sockRequest("GET", "/info", nil)
  1290. if err != nil {
  1291. return 0, err
  1292. }
  1293. if status != http.StatusOK {
  1294. return 0, fmt.Errorf("http status code: %d", status)
  1295. }
  1296. if err := json.Unmarshal(b, &i); err != nil {
  1297. return 0, err
  1298. }
  1299. return i.NGoroutines, nil
  1300. }
  1301. func waitForGoroutines(expected int) error {
  1302. t := time.After(30 * time.Second)
  1303. for {
  1304. select {
  1305. case <-t:
  1306. n, err := getGoroutineNumber()
  1307. if err != nil {
  1308. return err
  1309. }
  1310. if n > expected {
  1311. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  1312. }
  1313. default:
  1314. n, err := getGoroutineNumber()
  1315. if err != nil {
  1316. return err
  1317. }
  1318. if n <= expected {
  1319. return nil
  1320. }
  1321. time.Sleep(200 * time.Millisecond)
  1322. }
  1323. }
  1324. }
  1325. // getErrorMessage returns the error message from an error API response
  1326. func getErrorMessage(c *check.C, body []byte) string {
  1327. var resp types.ErrorResponse
  1328. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  1329. return strings.TrimSpace(resp.Message)
  1330. }
  1331. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  1332. after := time.After(timeout)
  1333. for {
  1334. v, comment := f(c)
  1335. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  1336. select {
  1337. case <-after:
  1338. assert = true
  1339. default:
  1340. }
  1341. if assert {
  1342. if comment != nil {
  1343. args = append(args, comment)
  1344. }
  1345. c.Assert(v, checker, args...)
  1346. return
  1347. }
  1348. time.Sleep(100 * time.Millisecond)
  1349. }
  1350. }
  1351. type checkF func(*check.C) (interface{}, check.CommentInterface)
  1352. type reducer func(...interface{}) interface{}
  1353. func reducedCheck(r reducer, funcs ...checkF) checkF {
  1354. return func(c *check.C) (interface{}, check.CommentInterface) {
  1355. var values []interface{}
  1356. var comments []string
  1357. for _, f := range funcs {
  1358. v, comment := f(c)
  1359. values = append(values, v)
  1360. if comment != nil {
  1361. comments = append(comments, comment.CheckCommentString())
  1362. }
  1363. }
  1364. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  1365. }
  1366. }
  1367. func sumAsIntegers(vals ...interface{}) interface{} {
  1368. var s int
  1369. for _, v := range vals {
  1370. s += v.(int)
  1371. }
  1372. return s
  1373. }