daemon_test.go 16 KB

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