daemon_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package daemon // import "github.com/docker/docker/integration/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "syscall"
  12. "testing"
  13. "github.com/docker/docker/api/types"
  14. containertypes "github.com/docker/docker/api/types/container"
  15. "github.com/docker/docker/api/types/mount"
  16. "github.com/docker/docker/api/types/volume"
  17. "github.com/docker/docker/daemon/config"
  18. "github.com/docker/docker/integration/internal/container"
  19. "github.com/docker/docker/testutil/daemon"
  20. "gotest.tools/v3/assert"
  21. is "gotest.tools/v3/assert/cmp"
  22. "gotest.tools/v3/icmd"
  23. "gotest.tools/v3/poll"
  24. "gotest.tools/v3/skip"
  25. )
  26. func TestConfigDaemonID(t *testing.T) {
  27. skip.If(t, runtime.GOOS == "windows")
  28. d := daemon.New(t)
  29. defer d.Stop(t)
  30. d.Start(t, "--iptables=false")
  31. info := d.Info(t)
  32. assert.Check(t, info.ID != "")
  33. d.Stop(t)
  34. // Verify that (if present) the engine-id file takes precedence
  35. const engineID = "this-is-the-engine-id"
  36. idFile := filepath.Join(d.RootDir(), "engine-id")
  37. assert.Check(t, os.Remove(idFile))
  38. // Using 0644 to allow rootless daemons to read the file (ideally
  39. // we'd chown the file to have the remapped user as owner).
  40. err := os.WriteFile(idFile, []byte(engineID), 0o644)
  41. assert.NilError(t, err)
  42. d.Start(t, "--iptables=false")
  43. info = d.Info(t)
  44. assert.Equal(t, info.ID, engineID)
  45. d.Stop(t)
  46. }
  47. func TestDaemonConfigValidation(t *testing.T) {
  48. skip.If(t, runtime.GOOS == "windows")
  49. d := daemon.New(t)
  50. dockerBinary, err := d.BinaryPath()
  51. assert.NilError(t, err)
  52. params := []string{"--validate", "--config-file"}
  53. dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
  54. if dest == "" {
  55. dest = os.Getenv("DEST")
  56. }
  57. testdata := filepath.Join(dest, "..", "..", "integration", "daemon", "testdata")
  58. const (
  59. validOut = "configuration OK"
  60. failedOut = "unable to configure the Docker daemon with file"
  61. )
  62. tests := []struct {
  63. name string
  64. args []string
  65. expectedOut string
  66. }{
  67. {
  68. name: "config with no content",
  69. args: append(params, filepath.Join(testdata, "empty-config-1.json")),
  70. expectedOut: validOut,
  71. },
  72. {
  73. name: "config with {}",
  74. args: append(params, filepath.Join(testdata, "empty-config-2.json")),
  75. expectedOut: validOut,
  76. },
  77. {
  78. name: "invalid config",
  79. args: append(params, filepath.Join(testdata, "invalid-config-1.json")),
  80. expectedOut: failedOut,
  81. },
  82. {
  83. name: "malformed config",
  84. args: append(params, filepath.Join(testdata, "malformed-config.json")),
  85. expectedOut: failedOut,
  86. },
  87. {
  88. name: "valid config",
  89. args: append(params, filepath.Join(testdata, "valid-config-1.json")),
  90. expectedOut: validOut,
  91. },
  92. }
  93. for _, tc := range tests {
  94. tc := tc
  95. t.Run(tc.name, func(t *testing.T) {
  96. t.Parallel()
  97. cmd := exec.Command(dockerBinary, tc.args...)
  98. out, err := cmd.CombinedOutput()
  99. assert.Check(t, is.Contains(string(out), tc.expectedOut))
  100. if tc.expectedOut == failedOut {
  101. assert.ErrorContains(t, err, "", "expected an error, but got none")
  102. } else {
  103. assert.NilError(t, err)
  104. }
  105. })
  106. }
  107. }
  108. func TestConfigDaemonSeccompProfiles(t *testing.T) {
  109. skip.If(t, runtime.GOOS == "windows")
  110. d := daemon.New(t)
  111. defer d.Stop(t)
  112. tests := []struct {
  113. doc string
  114. profile string
  115. expectedProfile string
  116. }{
  117. {
  118. doc: "empty profile set",
  119. profile: "",
  120. expectedProfile: config.SeccompProfileDefault,
  121. },
  122. {
  123. doc: "default profile",
  124. profile: config.SeccompProfileDefault,
  125. expectedProfile: config.SeccompProfileDefault,
  126. },
  127. {
  128. doc: "unconfined profile",
  129. profile: config.SeccompProfileUnconfined,
  130. expectedProfile: config.SeccompProfileUnconfined,
  131. },
  132. }
  133. for _, tc := range tests {
  134. tc := tc
  135. t.Run(tc.doc, func(t *testing.T) {
  136. d.Start(t, "--seccomp-profile="+tc.profile)
  137. info := d.Info(t)
  138. assert.Assert(t, is.Contains(info.SecurityOptions, "name=seccomp,profile="+tc.expectedProfile))
  139. d.Stop(t)
  140. cfg := filepath.Join(d.RootDir(), "daemon.json")
  141. err := os.WriteFile(cfg, []byte(`{"seccomp-profile": "`+tc.profile+`"}`), 0o644)
  142. assert.NilError(t, err)
  143. d.Start(t, "--config-file", cfg)
  144. info = d.Info(t)
  145. assert.Assert(t, is.Contains(info.SecurityOptions, "name=seccomp,profile="+tc.expectedProfile))
  146. d.Stop(t)
  147. })
  148. }
  149. }
  150. func TestDaemonProxy(t *testing.T) {
  151. skip.If(t, runtime.GOOS == "windows", "cannot start multiple daemons on windows")
  152. skip.If(t, os.Getenv("DOCKER_ROOTLESS") != "", "cannot connect to localhost proxy in rootless environment")
  153. newProxy := func(rcvd *string, t *testing.T) *httptest.Server {
  154. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  155. *rcvd = r.Host
  156. w.Header().Set("Content-Type", "application/json")
  157. _, _ = w.Write([]byte("OK"))
  158. }))
  159. t.Cleanup(s.Close)
  160. return s
  161. }
  162. const userPass = "myuser:mypassword@"
  163. // Configure proxy through env-vars
  164. t.Run("environment variables", func(t *testing.T) {
  165. t.Parallel()
  166. ctx := context.Background()
  167. var received string
  168. proxyServer := newProxy(&received, t)
  169. d := daemon.New(t, daemon.WithEnvVars(
  170. "HTTP_PROXY="+proxyServer.URL,
  171. "HTTPS_PROXY="+proxyServer.URL,
  172. "NO_PROXY=example.com",
  173. ))
  174. c := d.NewClientT(t)
  175. d.Start(t, "--iptables=false")
  176. defer d.Stop(t)
  177. info := d.Info(t)
  178. assert.Check(t, is.Equal(info.HTTPProxy, proxyServer.URL))
  179. assert.Check(t, is.Equal(info.HTTPSProxy, proxyServer.URL))
  180. assert.Check(t, is.Equal(info.NoProxy, "example.com"))
  181. _, err := c.ImagePull(ctx, "example.org:5000/some/image:latest", types.ImagePullOptions{})
  182. assert.ErrorContains(t, err, "", "pulling should have failed")
  183. assert.Equal(t, received, "example.org:5000")
  184. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  185. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  186. assert.ErrorContains(t, err, "", "pulling should have failed")
  187. assert.Equal(t, received, "example.org:5000", "should not have used proxy")
  188. })
  189. // Configure proxy through command-line flags
  190. t.Run("command-line options", func(t *testing.T) {
  191. t.Parallel()
  192. ctx := context.Background()
  193. var received string
  194. proxyServer := newProxy(&received, t)
  195. d := daemon.New(t, daemon.WithEnvVars(
  196. "HTTP_PROXY="+"http://"+userPass+"from-env-http.invalid",
  197. "http_proxy="+"http://"+userPass+"from-env-http.invalid",
  198. "HTTPS_PROXY="+"https://"+userPass+"myuser:mypassword@from-env-https-invalid",
  199. "https_proxy="+"https://"+userPass+"myuser:mypassword@from-env-https-invalid",
  200. "NO_PROXY=ignore.invalid",
  201. "no_proxy=ignore.invalid",
  202. ))
  203. d.Start(t, "--iptables=false", "--http-proxy", proxyServer.URL, "--https-proxy", proxyServer.URL, "--no-proxy", "example.com")
  204. defer d.Stop(t)
  205. c := d.NewClientT(t)
  206. info := d.Info(t)
  207. assert.Check(t, is.Equal(info.HTTPProxy, proxyServer.URL))
  208. assert.Check(t, is.Equal(info.HTTPSProxy, proxyServer.URL))
  209. assert.Check(t, is.Equal(info.NoProxy, "example.com"))
  210. ok, _ := d.ScanLogsT(ctx, t, daemon.ScanLogsMatchAll(
  211. "overriding existing proxy variable with value from configuration",
  212. "http_proxy",
  213. "HTTP_PROXY",
  214. "https_proxy",
  215. "HTTPS_PROXY",
  216. "no_proxy",
  217. "NO_PROXY",
  218. ))
  219. assert.Assert(t, ok)
  220. ok, logs := d.ScanLogsT(ctx, t, daemon.ScanLogsMatchString(userPass))
  221. assert.Assert(t, !ok, "logs should not contain the non-sanitized proxy URL: %s", logs)
  222. _, err := c.ImagePull(ctx, "example.org:5001/some/image:latest", types.ImagePullOptions{})
  223. assert.ErrorContains(t, err, "", "pulling should have failed")
  224. assert.Equal(t, received, "example.org:5001")
  225. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  226. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  227. assert.ErrorContains(t, err, "", "pulling should have failed")
  228. assert.Equal(t, received, "example.org:5001", "should not have used proxy")
  229. })
  230. // Configure proxy through configuration file
  231. t.Run("configuration file", func(t *testing.T) {
  232. t.Parallel()
  233. ctx := context.Background()
  234. var received string
  235. proxyServer := newProxy(&received, t)
  236. d := daemon.New(t, daemon.WithEnvVars(
  237. "HTTP_PROXY="+"http://"+userPass+"from-env-http.invalid",
  238. "http_proxy="+"http://"+userPass+"from-env-http.invalid",
  239. "HTTPS_PROXY="+"https://"+userPass+"myuser:mypassword@from-env-https-invalid",
  240. "https_proxy="+"https://"+userPass+"myuser:mypassword@from-env-https-invalid",
  241. "NO_PROXY=ignore.invalid",
  242. "no_proxy=ignore.invalid",
  243. ))
  244. c := d.NewClientT(t)
  245. configFile := filepath.Join(d.RootDir(), "daemon.json")
  246. configJSON := fmt.Sprintf(`{"proxies":{"http-proxy":%[1]q, "https-proxy": %[1]q, "no-proxy": "example.com"}}`, proxyServer.URL)
  247. assert.NilError(t, os.WriteFile(configFile, []byte(configJSON), 0o644))
  248. d.Start(t, "--iptables=false", "--config-file", configFile)
  249. defer d.Stop(t)
  250. info := d.Info(t)
  251. assert.Check(t, is.Equal(info.HTTPProxy, proxyServer.URL))
  252. assert.Check(t, is.Equal(info.HTTPSProxy, proxyServer.URL))
  253. assert.Check(t, is.Equal(info.NoProxy, "example.com"))
  254. d.ScanLogsT(ctx, t, daemon.ScanLogsMatchAll(
  255. "overriding existing proxy variable with value from configuration",
  256. "http_proxy",
  257. "HTTP_PROXY",
  258. "https_proxy",
  259. "HTTPS_PROXY",
  260. "no_proxy",
  261. "NO_PROXY",
  262. ))
  263. _, err := c.ImagePull(ctx, "example.org:5002/some/image:latest", types.ImagePullOptions{})
  264. assert.ErrorContains(t, err, "", "pulling should have failed")
  265. assert.Equal(t, received, "example.org:5002")
  266. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  267. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  268. assert.ErrorContains(t, err, "", "pulling should have failed")
  269. assert.Equal(t, received, "example.org:5002", "should not have used proxy")
  270. })
  271. // Conflicting options (passed both through command-line options and config file)
  272. t.Run("conflicting options", func(t *testing.T) {
  273. ctx := context.Background()
  274. const (
  275. proxyRawURL = "https://" + userPass + "example.org"
  276. proxyURL = "https://xxxxx:xxxxx@example.org"
  277. )
  278. d := daemon.New(t)
  279. configFile := filepath.Join(d.RootDir(), "daemon.json")
  280. configJSON := fmt.Sprintf(`{"proxies":{"http-proxy":%[1]q, "https-proxy": %[1]q, "no-proxy": "example.com"}}`, proxyRawURL)
  281. assert.NilError(t, os.WriteFile(configFile, []byte(configJSON), 0o644))
  282. err := d.StartWithError("--http-proxy", proxyRawURL, "--https-proxy", proxyRawURL, "--no-proxy", "example.com", "--config-file", configFile, "--validate")
  283. assert.ErrorContains(t, err, "daemon exited during startup")
  284. expected := fmt.Sprintf(
  285. `the following directives are specified both as a flag and in the configuration file: http-proxy: (from flag: %[1]s, from file: %[1]s), https-proxy: (from flag: %[1]s, from file: %[1]s), no-proxy: (from flag: example.com, from file: example.com)`,
  286. proxyURL,
  287. )
  288. poll.WaitOn(t, d.PollCheckLogs(ctx, daemon.ScanLogsMatchString(expected)))
  289. })
  290. // Make sure values are sanitized when reloading the daemon-config
  291. t.Run("reload sanitized", func(t *testing.T) {
  292. t.Parallel()
  293. ctx := context.Background()
  294. const (
  295. proxyRawURL = "https://" + userPass + "example.org"
  296. proxyURL = "https://xxxxx:xxxxx@example.org"
  297. )
  298. d := daemon.New(t)
  299. d.Start(t, "--iptables=false", "--http-proxy", proxyRawURL, "--https-proxy", proxyRawURL, "--no-proxy", "example.com")
  300. defer d.Stop(t)
  301. err := d.Signal(syscall.SIGHUP)
  302. assert.NilError(t, err)
  303. poll.WaitOn(t, d.PollCheckLogs(ctx, daemon.ScanLogsMatchAll("Reloaded configuration:", proxyURL)))
  304. ok, logs := d.ScanLogsT(ctx, t, daemon.ScanLogsMatchString(userPass))
  305. assert.Assert(t, !ok, "logs should not contain the non-sanitized proxy URL: %s", logs)
  306. })
  307. }
  308. func TestLiveRestore(t *testing.T) {
  309. skip.If(t, runtime.GOOS == "windows", "cannot start multiple daemons on windows")
  310. t.Run("volume references", testLiveRestoreVolumeReferences)
  311. }
  312. func testLiveRestoreVolumeReferences(t *testing.T) {
  313. t.Parallel()
  314. d := daemon.New(t)
  315. d.StartWithBusybox(t, "--live-restore", "--iptables=false")
  316. defer func() {
  317. d.Stop(t)
  318. d.Cleanup(t)
  319. }()
  320. c := d.NewClientT(t)
  321. ctx := context.Background()
  322. runTest := func(t *testing.T, policy containertypes.RestartPolicyMode) {
  323. t.Run(string(policy), func(t *testing.T) {
  324. volName := "test-live-restore-volume-references-" + string(policy)
  325. _, err := c.VolumeCreate(ctx, volume.CreateOptions{Name: volName})
  326. assert.NilError(t, err)
  327. // Create a container that uses the volume
  328. m := mount.Mount{
  329. Type: mount.TypeVolume,
  330. Source: volName,
  331. Target: "/foo",
  332. }
  333. cID := container.Run(ctx, t, c, container.WithMount(m), container.WithCmd("top"), container.WithRestartPolicy(policy))
  334. defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  335. // Stop the daemon
  336. d.Restart(t, "--live-restore", "--iptables=false")
  337. // Try to remove the volume
  338. err = c.VolumeRemove(ctx, volName, false)
  339. assert.ErrorContains(t, err, "volume is in use")
  340. _, err = c.VolumeInspect(ctx, volName)
  341. assert.NilError(t, err)
  342. })
  343. }
  344. t.Run("restartPolicy", func(t *testing.T) {
  345. runTest(t, containertypes.RestartPolicyAlways)
  346. runTest(t, containertypes.RestartPolicyUnlessStopped)
  347. runTest(t, containertypes.RestartPolicyOnFailure)
  348. runTest(t, containertypes.RestartPolicyDisabled)
  349. })
  350. // Make sure that the local volume driver's mount ref count is restored
  351. // Addresses https://github.com/moby/moby/issues/44422
  352. t.Run("local volume with mount options", func(t *testing.T) {
  353. v, err := c.VolumeCreate(ctx, volume.CreateOptions{
  354. Driver: "local",
  355. Name: "test-live-restore-volume-references-local",
  356. DriverOpts: map[string]string{
  357. "type": "tmpfs",
  358. "device": "tmpfs",
  359. },
  360. })
  361. assert.NilError(t, err)
  362. m := mount.Mount{
  363. Type: mount.TypeVolume,
  364. Source: v.Name,
  365. Target: "/foo",
  366. }
  367. cID := container.Run(ctx, t, c, container.WithMount(m), container.WithCmd("top"))
  368. defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  369. d.Restart(t, "--live-restore", "--iptables=false")
  370. // Try to remove the volume
  371. // This should fail since its used by a container
  372. err = c.VolumeRemove(ctx, v.Name, false)
  373. assert.ErrorContains(t, err, "volume is in use")
  374. // Remove that container which should free the references in the volume
  375. err = c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  376. assert.NilError(t, err)
  377. // Now we should be able to remove the volume
  378. err = c.VolumeRemove(ctx, v.Name, false)
  379. assert.NilError(t, err)
  380. })
  381. // Make sure that we don't panic if the container has bind-mounts
  382. // (which should not be "restored")
  383. // Regression test for https://github.com/moby/moby/issues/45898
  384. t.Run("container with bind-mounts", func(t *testing.T) {
  385. m := mount.Mount{
  386. Type: mount.TypeBind,
  387. Source: os.TempDir(),
  388. Target: "/foo",
  389. }
  390. cID := container.Run(ctx, t, c, container.WithMount(m), container.WithCmd("top"))
  391. defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  392. d.Restart(t, "--live-restore", "--iptables=false")
  393. err := c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  394. assert.NilError(t, err)
  395. })
  396. }
  397. func TestDaemonDefaultBridgeWithFixedCidrButNoBip(t *testing.T) {
  398. skip.If(t, runtime.GOOS == "windows")
  399. bridgeName := "ext-bridge1"
  400. d := daemon.New(t, daemon.WithEnvVars("DOCKER_TEST_CREATE_DEFAULT_BRIDGE="+bridgeName))
  401. defer func() {
  402. d.Stop(t)
  403. d.Cleanup(t)
  404. }()
  405. defer func() {
  406. // No need to clean up when running this test in rootless mode, as the
  407. // interface is deleted when the daemon is stopped and the netns
  408. // reclaimed by the kernel.
  409. if !testEnv.IsRootless() {
  410. deleteInterface(t, bridgeName)
  411. }
  412. }()
  413. d.StartWithBusybox(t, "--bridge", bridgeName, "--fixed-cidr", "192.168.130.0/24")
  414. }
  415. func deleteInterface(t *testing.T, ifName string) {
  416. icmd.RunCommand("ip", "link", "delete", ifName).Assert(t, icmd.Success)
  417. icmd.RunCommand("iptables", "-t", "nat", "--flush").Assert(t, icmd.Success)
  418. icmd.RunCommand("iptables", "--flush").Assert(t, icmd.Success)
  419. }