create_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package container // import "github.com/docker/docker/integration/container"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "testing"
  9. "time"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/network"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/client"
  15. ctr "github.com/docker/docker/integration/internal/container"
  16. "github.com/docker/docker/internal/test/request"
  17. "github.com/docker/docker/oci"
  18. "gotest.tools/assert"
  19. is "gotest.tools/assert/cmp"
  20. "gotest.tools/poll"
  21. "gotest.tools/skip"
  22. )
  23. func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
  24. defer setupTest(t)()
  25. client := testEnv.APIClient()
  26. testCases := []struct {
  27. doc string
  28. image string
  29. expectedError string
  30. }{
  31. {
  32. doc: "image and tag",
  33. image: "test456:v1",
  34. expectedError: "No such image: test456:v1",
  35. },
  36. {
  37. doc: "image no tag",
  38. image: "test456",
  39. expectedError: "No such image: test456",
  40. },
  41. {
  42. doc: "digest",
  43. image: "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  44. expectedError: "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  45. },
  46. }
  47. for _, tc := range testCases {
  48. tc := tc
  49. t.Run(tc.doc, func(t *testing.T) {
  50. t.Parallel()
  51. _, err := client.ContainerCreate(context.Background(),
  52. &container.Config{Image: tc.image},
  53. &container.HostConfig{},
  54. &network.NetworkingConfig{},
  55. "",
  56. )
  57. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  58. })
  59. }
  60. }
  61. func TestCreateWithInvalidEnv(t *testing.T) {
  62. defer setupTest(t)()
  63. client := testEnv.APIClient()
  64. testCases := []struct {
  65. env string
  66. expectedError string
  67. }{
  68. {
  69. env: "",
  70. expectedError: "invalid environment variable:",
  71. },
  72. {
  73. env: "=",
  74. expectedError: "invalid environment variable: =",
  75. },
  76. {
  77. env: "=foo",
  78. expectedError: "invalid environment variable: =foo",
  79. },
  80. }
  81. for index, tc := range testCases {
  82. tc := tc
  83. t.Run(strconv.Itoa(index), func(t *testing.T) {
  84. t.Parallel()
  85. _, err := client.ContainerCreate(context.Background(),
  86. &container.Config{
  87. Image: "busybox",
  88. Env: []string{tc.env},
  89. },
  90. &container.HostConfig{},
  91. &network.NetworkingConfig{},
  92. "",
  93. )
  94. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  95. })
  96. }
  97. }
  98. // Test case for #30166 (target was not validated)
  99. func TestCreateTmpfsMountsTarget(t *testing.T) {
  100. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  101. defer setupTest(t)()
  102. client := testEnv.APIClient()
  103. testCases := []struct {
  104. target string
  105. expectedError string
  106. }{
  107. {
  108. target: ".",
  109. expectedError: "mount path must be absolute",
  110. },
  111. {
  112. target: "foo",
  113. expectedError: "mount path must be absolute",
  114. },
  115. {
  116. target: "/",
  117. expectedError: "destination can't be '/'",
  118. },
  119. {
  120. target: "//",
  121. expectedError: "destination can't be '/'",
  122. },
  123. }
  124. for _, tc := range testCases {
  125. _, err := client.ContainerCreate(context.Background(),
  126. &container.Config{
  127. Image: "busybox",
  128. },
  129. &container.HostConfig{
  130. Tmpfs: map[string]string{tc.target: ""},
  131. },
  132. &network.NetworkingConfig{},
  133. "",
  134. )
  135. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  136. }
  137. }
  138. func TestCreateWithCustomMaskedPaths(t *testing.T) {
  139. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  140. defer setupTest(t)()
  141. client := testEnv.APIClient()
  142. ctx := context.Background()
  143. testCases := []struct {
  144. maskedPaths []string
  145. expected []string
  146. }{
  147. {
  148. maskedPaths: []string{},
  149. expected: []string{},
  150. },
  151. {
  152. maskedPaths: nil,
  153. expected: oci.DefaultSpec().Linux.MaskedPaths,
  154. },
  155. {
  156. maskedPaths: []string{"/proc/kcore", "/proc/keys"},
  157. expected: []string{"/proc/kcore", "/proc/keys"},
  158. },
  159. }
  160. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  161. _, b, err := client.ContainerInspectWithRaw(ctx, name, false)
  162. assert.NilError(t, err)
  163. var inspectJSON map[string]interface{}
  164. err = json.Unmarshal(b, &inspectJSON)
  165. assert.NilError(t, err)
  166. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  167. assert.Check(t, is.Equal(true, ok), name)
  168. maskedPaths, ok := cfg["MaskedPaths"].([]interface{})
  169. assert.Check(t, is.Equal(true, ok), name)
  170. mps := []string{}
  171. for _, mp := range maskedPaths {
  172. mps = append(mps, mp.(string))
  173. }
  174. assert.DeepEqual(t, expected, mps)
  175. }
  176. for i, tc := range testCases {
  177. name := fmt.Sprintf("create-masked-paths-%d", i)
  178. config := container.Config{
  179. Image: "busybox",
  180. Cmd: []string{"true"},
  181. }
  182. hc := container.HostConfig{}
  183. if tc.maskedPaths != nil {
  184. hc.MaskedPaths = tc.maskedPaths
  185. }
  186. // Create the container.
  187. c, err := client.ContainerCreate(context.Background(),
  188. &config,
  189. &hc,
  190. &network.NetworkingConfig{},
  191. name,
  192. )
  193. assert.NilError(t, err)
  194. checkInspect(t, ctx, name, tc.expected)
  195. // Start the container.
  196. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  197. assert.NilError(t, err)
  198. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  199. checkInspect(t, ctx, name, tc.expected)
  200. }
  201. }
  202. func TestCreateWithCapabilities(t *testing.T) {
  203. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME: test should be able to run on LCOW")
  204. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "Capabilities was added in API v1.40")
  205. defer setupTest(t)()
  206. ctx := context.Background()
  207. clientNew := request.NewAPIClient(t)
  208. clientOld := request.NewAPIClient(t, client.WithVersion("1.39"))
  209. testCases := []struct {
  210. doc string
  211. hostConfig container.HostConfig
  212. expected []string
  213. expectedError string
  214. oldClient bool
  215. }{
  216. {
  217. doc: "no capabilities",
  218. hostConfig: container.HostConfig{},
  219. },
  220. {
  221. doc: "empty capabilities",
  222. hostConfig: container.HostConfig{
  223. Capabilities: []string{},
  224. },
  225. expected: []string{},
  226. },
  227. {
  228. doc: "valid capabilities",
  229. hostConfig: container.HostConfig{
  230. Capabilities: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  231. },
  232. expected: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  233. },
  234. {
  235. doc: "invalid capabilities",
  236. hostConfig: container.HostConfig{
  237. Capabilities: []string{"NET_RAW"},
  238. },
  239. expectedError: `invalid Capabilities: unknown capability: "NET_RAW"`,
  240. },
  241. {
  242. doc: "duplicate capabilities",
  243. hostConfig: container.HostConfig{
  244. Capabilities: []string{"CAP_SYS_NICE", "CAP_SYS_NICE"},
  245. },
  246. expected: []string{"CAP_SYS_NICE", "CAP_SYS_NICE"},
  247. },
  248. {
  249. doc: "capabilities API v1.39",
  250. hostConfig: container.HostConfig{
  251. Capabilities: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  252. },
  253. expected: nil,
  254. oldClient: true,
  255. },
  256. {
  257. doc: "empty capadd",
  258. hostConfig: container.HostConfig{
  259. Capabilities: []string{"CAP_NET_ADMIN"},
  260. CapAdd: []string{},
  261. },
  262. expected: []string{"CAP_NET_ADMIN"},
  263. },
  264. {
  265. doc: "empty capdrop",
  266. hostConfig: container.HostConfig{
  267. Capabilities: []string{"CAP_NET_ADMIN"},
  268. CapDrop: []string{},
  269. },
  270. expected: []string{"CAP_NET_ADMIN"},
  271. },
  272. {
  273. doc: "capadd capdrop",
  274. hostConfig: container.HostConfig{
  275. CapAdd: []string{"SYS_NICE", "CAP_SYS_NICE"},
  276. CapDrop: []string{"SYS_NICE", "CAP_SYS_NICE"},
  277. },
  278. },
  279. {
  280. doc: "conflict with capadd",
  281. hostConfig: container.HostConfig{
  282. Capabilities: []string{"CAP_NET_ADMIN"},
  283. CapAdd: []string{"SYS_NICE"},
  284. },
  285. expectedError: `conflicting options: Capabilities and CapAdd`,
  286. },
  287. {
  288. doc: "conflict with capdrop",
  289. hostConfig: container.HostConfig{
  290. Capabilities: []string{"CAP_NET_ADMIN"},
  291. CapDrop: []string{"NET_RAW"},
  292. },
  293. expectedError: `conflicting options: Capabilities and CapDrop`,
  294. },
  295. }
  296. for _, tc := range testCases {
  297. tc := tc
  298. t.Run(tc.doc, func(t *testing.T) {
  299. t.Parallel()
  300. client := clientNew
  301. if tc.oldClient {
  302. client = clientOld
  303. }
  304. c, err := client.ContainerCreate(context.Background(),
  305. &container.Config{Image: "busybox"},
  306. &tc.hostConfig,
  307. &network.NetworkingConfig{},
  308. "",
  309. )
  310. if tc.expectedError == "" {
  311. assert.NilError(t, err)
  312. ci, err := client.ContainerInspect(ctx, c.ID)
  313. assert.NilError(t, err)
  314. assert.Check(t, ci.HostConfig != nil)
  315. assert.DeepEqual(t, tc.expected, ci.HostConfig.Capabilities)
  316. } else {
  317. assert.ErrorContains(t, err, tc.expectedError)
  318. }
  319. })
  320. }
  321. }
  322. func TestCreateWithCustomReadonlyPaths(t *testing.T) {
  323. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  324. defer setupTest(t)()
  325. client := testEnv.APIClient()
  326. ctx := context.Background()
  327. testCases := []struct {
  328. doc string
  329. readonlyPaths []string
  330. expected []string
  331. }{
  332. {
  333. readonlyPaths: []string{},
  334. expected: []string{},
  335. },
  336. {
  337. readonlyPaths: nil,
  338. expected: oci.DefaultSpec().Linux.ReadonlyPaths,
  339. },
  340. {
  341. readonlyPaths: []string{"/proc/asound", "/proc/bus"},
  342. expected: []string{"/proc/asound", "/proc/bus"},
  343. },
  344. }
  345. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  346. _, b, err := client.ContainerInspectWithRaw(ctx, name, false)
  347. assert.NilError(t, err)
  348. var inspectJSON map[string]interface{}
  349. err = json.Unmarshal(b, &inspectJSON)
  350. assert.NilError(t, err)
  351. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  352. assert.Check(t, is.Equal(true, ok), name)
  353. readonlyPaths, ok := cfg["ReadonlyPaths"].([]interface{})
  354. assert.Check(t, is.Equal(true, ok), name)
  355. rops := []string{}
  356. for _, rop := range readonlyPaths {
  357. rops = append(rops, rop.(string))
  358. }
  359. assert.DeepEqual(t, expected, rops)
  360. }
  361. for i, tc := range testCases {
  362. name := fmt.Sprintf("create-readonly-paths-%d", i)
  363. config := container.Config{
  364. Image: "busybox",
  365. Cmd: []string{"true"},
  366. }
  367. hc := container.HostConfig{}
  368. if tc.readonlyPaths != nil {
  369. hc.ReadonlyPaths = tc.readonlyPaths
  370. }
  371. // Create the container.
  372. c, err := client.ContainerCreate(context.Background(),
  373. &config,
  374. &hc,
  375. &network.NetworkingConfig{},
  376. name,
  377. )
  378. assert.NilError(t, err)
  379. checkInspect(t, ctx, name, tc.expected)
  380. // Start the container.
  381. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  382. assert.NilError(t, err)
  383. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  384. checkInspect(t, ctx, name, tc.expected)
  385. }
  386. }
  387. func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
  388. defer setupTest(t)()
  389. testCases := []struct {
  390. doc string
  391. interval time.Duration
  392. timeout time.Duration
  393. retries int
  394. startPeriod time.Duration
  395. expectedErr string
  396. }{
  397. {
  398. doc: "test invalid Interval in Healthcheck: less than 0s",
  399. interval: -10 * time.Millisecond,
  400. timeout: time.Second,
  401. retries: 1000,
  402. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  403. },
  404. {
  405. doc: "test invalid Interval in Healthcheck: larger than 0s but less than 1ms",
  406. interval: 500 * time.Microsecond,
  407. timeout: time.Second,
  408. retries: 1000,
  409. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  410. },
  411. {
  412. doc: "test invalid Timeout in Healthcheck: less than 1ms",
  413. interval: time.Second,
  414. timeout: -100 * time.Millisecond,
  415. retries: 1000,
  416. expectedErr: fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration),
  417. },
  418. {
  419. doc: "test invalid Retries in Healthcheck: less than 0",
  420. interval: time.Second,
  421. timeout: time.Second,
  422. retries: -10,
  423. expectedErr: "Retries in Healthcheck cannot be negative",
  424. },
  425. {
  426. doc: "test invalid StartPeriod in Healthcheck: not 0 and less than 1ms",
  427. interval: time.Second,
  428. timeout: time.Second,
  429. retries: 1000,
  430. startPeriod: 100 * time.Microsecond,
  431. expectedErr: fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration),
  432. },
  433. }
  434. for i, tc := range testCases {
  435. i := i
  436. tc := tc
  437. t.Run(tc.doc, func(t *testing.T) {
  438. t.Parallel()
  439. healthCheck := map[string]interface{}{
  440. "Interval": tc.interval,
  441. "Timeout": tc.timeout,
  442. "Retries": tc.retries,
  443. }
  444. if tc.startPeriod != 0 {
  445. healthCheck["StartPeriod"] = tc.startPeriod
  446. }
  447. config := map[string]interface{}{
  448. "Image": "busybox",
  449. "Healthcheck": healthCheck,
  450. }
  451. res, body, err := request.Post("/containers/create?name="+fmt.Sprintf("test_%d_", i)+t.Name(), request.JSONBody(config))
  452. assert.NilError(t, err)
  453. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  454. assert.Check(t, is.Equal(http.StatusInternalServerError, res.StatusCode))
  455. } else {
  456. assert.Check(t, is.Equal(http.StatusBadRequest, res.StatusCode))
  457. }
  458. buf, err := request.ReadBody(body)
  459. assert.NilError(t, err)
  460. assert.Check(t, is.Contains(string(buf), tc.expectedErr))
  461. })
  462. }
  463. }