docker_utils.go 43 KB

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