create_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. package container // import "github.com/docker/docker/integration/container"
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/containerd/containerd"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/api/types/versions"
  15. "github.com/docker/docker/client"
  16. "github.com/docker/docker/errdefs"
  17. ctr "github.com/docker/docker/integration/internal/container"
  18. net "github.com/docker/docker/integration/internal/network"
  19. "github.com/docker/docker/oci"
  20. "github.com/docker/docker/testutil"
  21. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  22. "gotest.tools/v3/assert"
  23. is "gotest.tools/v3/assert/cmp"
  24. "gotest.tools/v3/poll"
  25. "gotest.tools/v3/skip"
  26. )
  27. func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
  28. ctx := setupTest(t)
  29. client := testEnv.APIClient()
  30. testCases := []struct {
  31. doc string
  32. image string
  33. expectedError string
  34. }{
  35. {
  36. doc: "image and tag",
  37. image: "test456:v1",
  38. expectedError: "No such image: test456:v1",
  39. },
  40. {
  41. doc: "image no tag",
  42. image: "test456",
  43. expectedError: "No such image: test456",
  44. },
  45. {
  46. doc: "digest",
  47. image: "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  48. expectedError: "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  49. },
  50. }
  51. for _, tc := range testCases {
  52. tc := tc
  53. t.Run(tc.doc, func(t *testing.T) {
  54. t.Parallel()
  55. ctx := testutil.StartSpan(ctx, t)
  56. _, err := client.ContainerCreate(ctx,
  57. &container.Config{Image: tc.image},
  58. &container.HostConfig{},
  59. &network.NetworkingConfig{},
  60. nil,
  61. "",
  62. )
  63. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  64. assert.Check(t, errdefs.IsNotFound(err))
  65. })
  66. }
  67. }
  68. // TestCreateLinkToNonExistingContainer verifies that linking to a non-existing
  69. // container returns an "invalid parameter" (400) status, and not the underlying
  70. // "non exists" (404).
  71. func TestCreateLinkToNonExistingContainer(t *testing.T) {
  72. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "legacy links are not supported on windows")
  73. ctx := setupTest(t)
  74. c := testEnv.APIClient()
  75. _, err := c.ContainerCreate(ctx,
  76. &container.Config{
  77. Image: "busybox",
  78. },
  79. &container.HostConfig{
  80. Links: []string{"no-such-container"},
  81. },
  82. &network.NetworkingConfig{},
  83. nil,
  84. "",
  85. )
  86. assert.Check(t, is.ErrorContains(err, "could not get container for no-such-container"))
  87. assert.Check(t, errdefs.IsInvalidParameter(err))
  88. }
  89. func TestCreateWithInvalidEnv(t *testing.T) {
  90. ctx := setupTest(t)
  91. client := testEnv.APIClient()
  92. testCases := []struct {
  93. env string
  94. expectedError string
  95. }{
  96. {
  97. env: "",
  98. expectedError: "invalid environment variable:",
  99. },
  100. {
  101. env: "=",
  102. expectedError: "invalid environment variable: =",
  103. },
  104. {
  105. env: "=foo",
  106. expectedError: "invalid environment variable: =foo",
  107. },
  108. }
  109. for index, tc := range testCases {
  110. tc := tc
  111. t.Run(strconv.Itoa(index), func(t *testing.T) {
  112. t.Parallel()
  113. ctx := testutil.StartSpan(ctx, t)
  114. _, err := client.ContainerCreate(ctx,
  115. &container.Config{
  116. Image: "busybox",
  117. Env: []string{tc.env},
  118. },
  119. &container.HostConfig{},
  120. &network.NetworkingConfig{},
  121. nil,
  122. "",
  123. )
  124. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  125. assert.Check(t, errdefs.IsInvalidParameter(err))
  126. })
  127. }
  128. }
  129. // Test case for #30166 (target was not validated)
  130. func TestCreateTmpfsMountsTarget(t *testing.T) {
  131. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  132. ctx := setupTest(t)
  133. client := testEnv.APIClient()
  134. testCases := []struct {
  135. target string
  136. expectedError string
  137. }{
  138. {
  139. target: ".",
  140. expectedError: "mount path must be absolute",
  141. },
  142. {
  143. target: "foo",
  144. expectedError: "mount path must be absolute",
  145. },
  146. {
  147. target: "/",
  148. expectedError: "destination can't be '/'",
  149. },
  150. {
  151. target: "//",
  152. expectedError: "destination can't be '/'",
  153. },
  154. }
  155. for _, tc := range testCases {
  156. _, err := client.ContainerCreate(ctx,
  157. &container.Config{
  158. Image: "busybox",
  159. },
  160. &container.HostConfig{
  161. Tmpfs: map[string]string{tc.target: ""},
  162. },
  163. &network.NetworkingConfig{},
  164. nil,
  165. "",
  166. )
  167. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  168. assert.Check(t, errdefs.IsInvalidParameter(err))
  169. }
  170. }
  171. func TestCreateWithCustomMaskedPaths(t *testing.T) {
  172. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  173. ctx := setupTest(t)
  174. apiClient := testEnv.APIClient()
  175. testCases := []struct {
  176. maskedPaths []string
  177. expected []string
  178. }{
  179. {
  180. maskedPaths: []string{},
  181. expected: []string{},
  182. },
  183. {
  184. maskedPaths: nil,
  185. expected: oci.DefaultSpec().Linux.MaskedPaths,
  186. },
  187. {
  188. maskedPaths: []string{"/proc/kcore", "/proc/keys"},
  189. expected: []string{"/proc/kcore", "/proc/keys"},
  190. },
  191. }
  192. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  193. _, b, err := apiClient.ContainerInspectWithRaw(ctx, name, false)
  194. assert.NilError(t, err)
  195. var inspectJSON map[string]interface{}
  196. err = json.Unmarshal(b, &inspectJSON)
  197. assert.NilError(t, err)
  198. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  199. assert.Check(t, is.Equal(true, ok), name)
  200. maskedPaths, ok := cfg["MaskedPaths"].([]interface{})
  201. assert.Check(t, is.Equal(true, ok), name)
  202. mps := []string{}
  203. for _, mp := range maskedPaths {
  204. mps = append(mps, mp.(string))
  205. }
  206. assert.DeepEqual(t, expected, mps)
  207. }
  208. // TODO: This should be using subtests
  209. for i, tc := range testCases {
  210. name := fmt.Sprintf("create-masked-paths-%d", i)
  211. config := container.Config{
  212. Image: "busybox",
  213. Cmd: []string{"true"},
  214. }
  215. hc := container.HostConfig{}
  216. if tc.maskedPaths != nil {
  217. hc.MaskedPaths = tc.maskedPaths
  218. }
  219. // Create the container.
  220. c, err := apiClient.ContainerCreate(ctx,
  221. &config,
  222. &hc,
  223. &network.NetworkingConfig{},
  224. nil,
  225. name,
  226. )
  227. assert.NilError(t, err)
  228. checkInspect(t, ctx, name, tc.expected)
  229. // Start the container.
  230. err = apiClient.ContainerStart(ctx, c.ID, container.StartOptions{})
  231. assert.NilError(t, err)
  232. poll.WaitOn(t, ctr.IsInState(ctx, apiClient, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  233. checkInspect(t, ctx, name, tc.expected)
  234. }
  235. }
  236. func TestCreateWithCustomReadonlyPaths(t *testing.T) {
  237. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  238. ctx := setupTest(t)
  239. apiClient := testEnv.APIClient()
  240. testCases := []struct {
  241. readonlyPaths []string
  242. expected []string
  243. }{
  244. {
  245. readonlyPaths: []string{},
  246. expected: []string{},
  247. },
  248. {
  249. readonlyPaths: nil,
  250. expected: oci.DefaultSpec().Linux.ReadonlyPaths,
  251. },
  252. {
  253. readonlyPaths: []string{"/proc/asound", "/proc/bus"},
  254. expected: []string{"/proc/asound", "/proc/bus"},
  255. },
  256. }
  257. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  258. _, b, err := apiClient.ContainerInspectWithRaw(ctx, name, false)
  259. assert.NilError(t, err)
  260. var inspectJSON map[string]interface{}
  261. err = json.Unmarshal(b, &inspectJSON)
  262. assert.NilError(t, err)
  263. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  264. assert.Check(t, is.Equal(true, ok), name)
  265. readonlyPaths, ok := cfg["ReadonlyPaths"].([]interface{})
  266. assert.Check(t, is.Equal(true, ok), name)
  267. rops := []string{}
  268. for _, rop := range readonlyPaths {
  269. rops = append(rops, rop.(string))
  270. }
  271. assert.DeepEqual(t, expected, rops)
  272. }
  273. for i, tc := range testCases {
  274. name := fmt.Sprintf("create-readonly-paths-%d", i)
  275. config := container.Config{
  276. Image: "busybox",
  277. Cmd: []string{"true"},
  278. }
  279. hc := container.HostConfig{}
  280. if tc.readonlyPaths != nil {
  281. hc.ReadonlyPaths = tc.readonlyPaths
  282. }
  283. // Create the container.
  284. c, err := apiClient.ContainerCreate(ctx,
  285. &config,
  286. &hc,
  287. &network.NetworkingConfig{},
  288. nil,
  289. name,
  290. )
  291. assert.NilError(t, err)
  292. checkInspect(t, ctx, name, tc.expected)
  293. // Start the container.
  294. err = apiClient.ContainerStart(ctx, c.ID, container.StartOptions{})
  295. assert.NilError(t, err)
  296. poll.WaitOn(t, ctr.IsInState(ctx, apiClient, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  297. checkInspect(t, ctx, name, tc.expected)
  298. }
  299. }
  300. func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
  301. ctx := setupTest(t)
  302. apiClient := testEnv.APIClient()
  303. testCases := []struct {
  304. doc string
  305. interval time.Duration
  306. timeout time.Duration
  307. retries int
  308. startPeriod time.Duration
  309. startInterval time.Duration
  310. expectedErr string
  311. }{
  312. {
  313. doc: "test invalid Interval in Healthcheck: less than 0s",
  314. interval: -10 * time.Millisecond,
  315. timeout: time.Second,
  316. retries: 1000,
  317. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  318. },
  319. {
  320. doc: "test invalid Interval in Healthcheck: larger than 0s but less than 1ms",
  321. interval: 500 * time.Microsecond,
  322. timeout: time.Second,
  323. retries: 1000,
  324. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  325. },
  326. {
  327. doc: "test invalid Timeout in Healthcheck: less than 1ms",
  328. interval: time.Second,
  329. timeout: -100 * time.Millisecond,
  330. retries: 1000,
  331. expectedErr: fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration),
  332. },
  333. {
  334. doc: "test invalid Retries in Healthcheck: less than 0",
  335. interval: time.Second,
  336. timeout: time.Second,
  337. retries: -10,
  338. expectedErr: "Retries in Healthcheck cannot be negative",
  339. },
  340. {
  341. doc: "test invalid StartPeriod in Healthcheck: not 0 and less than 1ms",
  342. interval: time.Second,
  343. timeout: time.Second,
  344. retries: 1000,
  345. startPeriod: 100 * time.Microsecond,
  346. expectedErr: fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration),
  347. },
  348. {
  349. doc: "test invalid StartInterval in Healthcheck: not 0 and less than 1ms",
  350. interval: time.Second,
  351. timeout: time.Second,
  352. retries: 1000,
  353. startPeriod: time.Second,
  354. startInterval: 100 * time.Microsecond,
  355. expectedErr: fmt.Sprintf("StartInterval in Healthcheck cannot be less than %s", container.MinimumDuration),
  356. },
  357. }
  358. for _, tc := range testCases {
  359. tc := tc
  360. t.Run(tc.doc, func(t *testing.T) {
  361. t.Parallel()
  362. ctx := testutil.StartSpan(ctx, t)
  363. cfg := container.Config{
  364. Image: "busybox",
  365. Healthcheck: &container.HealthConfig{
  366. Interval: tc.interval,
  367. Timeout: tc.timeout,
  368. Retries: tc.retries,
  369. StartInterval: tc.startInterval,
  370. },
  371. }
  372. if tc.startPeriod != 0 {
  373. cfg.Healthcheck.StartPeriod = tc.startPeriod
  374. }
  375. resp, err := apiClient.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, nil, "")
  376. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  377. assert.Check(t, errdefs.IsInvalidParameter(err))
  378. assert.ErrorContains(t, err, tc.expectedErr)
  379. })
  380. }
  381. }
  382. // Make sure that anonymous volumes can be overritten by tmpfs
  383. // https://github.com/moby/moby/issues/40446
  384. func TestCreateTmpfsOverrideAnonymousVolume(t *testing.T) {
  385. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "windows does not support tmpfs")
  386. ctx := setupTest(t)
  387. apiClient := testEnv.APIClient()
  388. id := ctr.Create(ctx, t, apiClient,
  389. ctr.WithVolume("/foo"),
  390. ctr.WithTmpfs("/foo"),
  391. ctr.WithVolume("/bar"),
  392. ctr.WithTmpfs("/bar:size=999"),
  393. ctr.WithCmd("/bin/sh", "-c", "mount | grep '/foo' | grep tmpfs && mount | grep '/bar' | grep tmpfs"),
  394. )
  395. defer func() {
  396. err := apiClient.ContainerRemove(ctx, id, container.RemoveOptions{Force: true})
  397. assert.NilError(t, err)
  398. }()
  399. inspect, err := apiClient.ContainerInspect(ctx, id)
  400. assert.NilError(t, err)
  401. // tmpfs do not currently get added to inspect.Mounts
  402. // Normally an anonymous volume would, except now tmpfs should prevent that.
  403. assert.Assert(t, is.Len(inspect.Mounts, 0))
  404. chWait, chErr := apiClient.ContainerWait(ctx, id, container.WaitConditionNextExit)
  405. assert.NilError(t, apiClient.ContainerStart(ctx, id, container.StartOptions{}))
  406. timeout := time.NewTimer(30 * time.Second)
  407. defer timeout.Stop()
  408. select {
  409. case <-timeout.C:
  410. t.Fatal("timeout waiting for container to exit")
  411. case status := <-chWait:
  412. var errMsg string
  413. if status.Error != nil {
  414. errMsg = status.Error.Message
  415. }
  416. assert.Equal(t, int(status.StatusCode), 0, errMsg)
  417. case err := <-chErr:
  418. assert.NilError(t, err)
  419. }
  420. }
  421. // Test that if the referenced image platform does not match the requested platform on container create that we get an
  422. // error.
  423. func TestCreateDifferentPlatform(t *testing.T) {
  424. ctx := setupTest(t)
  425. apiClient := testEnv.APIClient()
  426. img, _, err := apiClient.ImageInspectWithRaw(ctx, "busybox:latest")
  427. assert.NilError(t, err)
  428. assert.Assert(t, img.Architecture != "")
  429. t.Run("different os", func(t *testing.T) {
  430. ctx := testutil.StartSpan(ctx, t)
  431. p := ocispec.Platform{
  432. OS: img.Os + "DifferentOS",
  433. Architecture: img.Architecture,
  434. Variant: img.Variant,
  435. }
  436. _, err := apiClient.ContainerCreate(ctx, &container.Config{Image: "busybox:latest"}, &container.HostConfig{}, nil, &p, "")
  437. assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
  438. })
  439. t.Run("different cpu arch", func(t *testing.T) {
  440. ctx := testutil.StartSpan(ctx, t)
  441. p := ocispec.Platform{
  442. OS: img.Os,
  443. Architecture: img.Architecture + "DifferentArch",
  444. Variant: img.Variant,
  445. }
  446. _, err := apiClient.ContainerCreate(ctx, &container.Config{Image: "busybox:latest"}, &container.HostConfig{}, nil, &p, "")
  447. assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
  448. })
  449. }
  450. func TestCreateVolumesFromNonExistingContainer(t *testing.T) {
  451. ctx := setupTest(t)
  452. cli := testEnv.APIClient()
  453. _, err := cli.ContainerCreate(
  454. ctx,
  455. &container.Config{Image: "busybox"},
  456. &container.HostConfig{VolumesFrom: []string{"nosuchcontainer"}},
  457. nil,
  458. nil,
  459. "",
  460. )
  461. assert.Check(t, errdefs.IsInvalidParameter(err))
  462. }
  463. // Test that we can create a container from an image that is for a different platform even if a platform was not specified
  464. // This is for the regression detailed here: https://github.com/moby/moby/issues/41552
  465. func TestCreatePlatformSpecificImageNoPlatform(t *testing.T) {
  466. ctx := setupTest(t)
  467. skip.If(t, testEnv.DaemonInfo.Architecture == "arm", "test only makes sense to run on non-arm systems")
  468. skip.If(t, testEnv.DaemonInfo.OSType != "linux", "test image is only available on linux")
  469. cli := testEnv.APIClient()
  470. _, err := cli.ContainerCreate(
  471. ctx,
  472. &container.Config{Image: "arm32v7/hello-world"},
  473. &container.HostConfig{},
  474. nil,
  475. nil,
  476. "",
  477. )
  478. assert.NilError(t, err)
  479. }
  480. func TestCreateInvalidHostConfig(t *testing.T) {
  481. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  482. ctx := setupTest(t)
  483. apiClient := testEnv.APIClient()
  484. testCases := []struct {
  485. doc string
  486. hc container.HostConfig
  487. expectedErr string
  488. }{
  489. {
  490. doc: "invalid IpcMode",
  491. hc: container.HostConfig{IpcMode: "invalid"},
  492. expectedErr: "Error response from daemon: invalid IPC mode: invalid",
  493. },
  494. {
  495. doc: "invalid PidMode",
  496. hc: container.HostConfig{PidMode: "invalid"},
  497. expectedErr: "Error response from daemon: invalid PID mode: invalid",
  498. },
  499. {
  500. doc: "invalid PidMode without container ID",
  501. hc: container.HostConfig{PidMode: "container"},
  502. expectedErr: "Error response from daemon: invalid PID mode: container",
  503. },
  504. {
  505. doc: "invalid UTSMode",
  506. hc: container.HostConfig{UTSMode: "invalid"},
  507. expectedErr: "Error response from daemon: invalid UTS mode: invalid",
  508. },
  509. {
  510. doc: "invalid Annotations",
  511. hc: container.HostConfig{Annotations: map[string]string{"": "a"}},
  512. expectedErr: "Error response from daemon: invalid Annotations: the empty string is not permitted as an annotation key",
  513. },
  514. }
  515. for _, tc := range testCases {
  516. tc := tc
  517. t.Run(tc.doc, func(t *testing.T) {
  518. t.Parallel()
  519. ctx := testutil.StartSpan(ctx, t)
  520. cfg := container.Config{
  521. Image: "busybox",
  522. }
  523. resp, err := apiClient.ContainerCreate(ctx, &cfg, &tc.hc, nil, nil, "")
  524. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  525. assert.Check(t, errdefs.IsInvalidParameter(err), "got: %T", err)
  526. assert.Error(t, err, tc.expectedErr)
  527. })
  528. }
  529. }
  530. func TestCreateWithMultipleEndpointSettings(t *testing.T) {
  531. ctx := setupTest(t)
  532. testcases := []struct {
  533. apiVersion string
  534. expectedErr string
  535. }{
  536. {apiVersion: "1.44"},
  537. {apiVersion: "1.43", expectedErr: "Container cannot be created with multiple network endpoints"},
  538. }
  539. for _, tc := range testcases {
  540. t.Run("with API v"+tc.apiVersion, func(t *testing.T) {
  541. apiClient, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion(tc.apiVersion))
  542. assert.NilError(t, err)
  543. config := container.Config{
  544. Image: "busybox",
  545. }
  546. networkingConfig := network.NetworkingConfig{
  547. EndpointsConfig: map[string]*network.EndpointSettings{
  548. "net1": {},
  549. "net2": {},
  550. "net3": {},
  551. },
  552. }
  553. _, err = apiClient.ContainerCreate(ctx, &config, &container.HostConfig{}, &networkingConfig, nil, "")
  554. if tc.expectedErr == "" {
  555. assert.NilError(t, err)
  556. } else {
  557. assert.ErrorContains(t, err, tc.expectedErr)
  558. }
  559. })
  560. }
  561. }
  562. func TestCreateWithCustomMACs(t *testing.T) {
  563. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  564. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.44"), "requires API v1.44")
  565. ctx := setupTest(t)
  566. apiClient := testEnv.APIClient()
  567. net.CreateNoError(ctx, t, apiClient, "testnet")
  568. attachCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
  569. defer cancel()
  570. res := ctr.RunAttach(attachCtx, t, apiClient,
  571. ctr.WithCmd("ip", "-o", "link", "show"),
  572. ctr.WithNetworkMode("bridge"),
  573. ctr.WithMacAddress("bridge", "02:32:1c:23:00:04"))
  574. assert.Equal(t, res.ExitCode, 0)
  575. assert.Equal(t, res.Stderr.String(), "")
  576. scanner := bufio.NewScanner(res.Stdout)
  577. for scanner.Scan() {
  578. fields := strings.Fields(scanner.Text())
  579. // The expected output is:
  580. // 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000\ link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  581. // 134: eth0@if135: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1400 qdisc noqueue \ link/ether 02:42:ac:11:00:04 brd ff:ff:ff:ff:ff:ff
  582. if len(fields) < 11 {
  583. continue
  584. }
  585. ifaceName := fields[1]
  586. if ifaceName[:3] != "eth" {
  587. continue
  588. }
  589. mac := fields[len(fields)-3]
  590. assert.Equal(t, mac, "02:32:1c:23:00:04")
  591. }
  592. }
  593. // Tests that when using containerd backed storage the containerd container has the image referenced stored.
  594. func TestContainerdContainerImageInfo(t *testing.T) {
  595. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.45"), "requires API v1.45")
  596. ctx := setupTest(t)
  597. apiClient := testEnv.APIClient()
  598. defer apiClient.Close()
  599. info, err := apiClient.Info(ctx)
  600. assert.NilError(t, err)
  601. skip.If(t, info.Containerd == nil, "requires containerd")
  602. // Currently a containerd container is only created when the container is started.
  603. // So start the container and then inspect the containerd container to verify the image info.
  604. id := ctr.Run(ctx, t, apiClient, func(cfg *ctr.TestContainerConfig) {
  605. // busybox is the default (as of this writing) used by the test client, but lets be explicit here.
  606. cfg.Config.Image = "busybox"
  607. })
  608. defer apiClient.ContainerRemove(ctx, id, container.RemoveOptions{Force: true})
  609. client, err := containerd.New(info.Containerd.Address, containerd.WithDefaultNamespace(info.Containerd.Namespaces.Containers))
  610. assert.NilError(t, err)
  611. defer client.Close()
  612. ctr, err := client.ContainerService().Get(ctx, id)
  613. assert.NilError(t, err)
  614. if testEnv.UsingSnapshotter() {
  615. assert.Equal(t, ctr.Image, "docker.io/library/busybox:latest")
  616. } else {
  617. // This field is not set when not using contianerd backed storage.
  618. assert.Equal(t, ctr.Image, "")
  619. }
  620. }