docker_utils.go 44 KB

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