daemon_unix_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //go:build !windows
  2. // +build !windows
  3. package daemon // import "github.com/docker/docker/daemon"
  4. import (
  5. "errors"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "testing"
  10. "github.com/docker/docker/api/types/blkiodev"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/config"
  14. "github.com/docker/docker/pkg/sysinfo"
  15. "golang.org/x/sys/unix"
  16. "gotest.tools/v3/assert"
  17. is "gotest.tools/v3/assert/cmp"
  18. )
  19. type fakeContainerGetter struct {
  20. containers map[string]*container.Container
  21. }
  22. func (f *fakeContainerGetter) GetContainer(cid string) (*container.Container, error) {
  23. ctr, ok := f.containers[cid]
  24. if !ok {
  25. return nil, errors.New("container not found")
  26. }
  27. return ctr, nil
  28. }
  29. // Unix test as uses settings which are not available on Windows
  30. func TestAdjustSharedNamespaceContainerName(t *testing.T) {
  31. fakeID := "abcdef1234567890"
  32. hostConfig := &containertypes.HostConfig{
  33. IpcMode: containertypes.IpcMode("container:base"),
  34. PidMode: containertypes.PidMode("container:base"),
  35. NetworkMode: containertypes.NetworkMode("container:base"),
  36. }
  37. containerStore := &fakeContainerGetter{}
  38. containerStore.containers = make(map[string]*container.Container)
  39. containerStore.containers["base"] = &container.Container{
  40. ID: fakeID,
  41. }
  42. adaptSharedNamespaceContainer(containerStore, hostConfig)
  43. if hostConfig.IpcMode != containertypes.IpcMode("container:"+fakeID) {
  44. t.Errorf("Expected IpcMode to be container:%s", fakeID)
  45. }
  46. if hostConfig.PidMode != containertypes.PidMode("container:"+fakeID) {
  47. t.Errorf("Expected PidMode to be container:%s", fakeID)
  48. }
  49. if hostConfig.NetworkMode != containertypes.NetworkMode("container:"+fakeID) {
  50. t.Errorf("Expected NetworkMode to be container:%s", fakeID)
  51. }
  52. }
  53. // Unix test as uses settings which are not available on Windows
  54. func TestAdjustCPUShares(t *testing.T) {
  55. tmp, err := ioutil.TempDir("", "docker-daemon-unix-test-")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. defer os.RemoveAll(tmp)
  60. daemon := &Daemon{
  61. repository: tmp,
  62. root: tmp,
  63. }
  64. muteLogs()
  65. hostConfig := &containertypes.HostConfig{
  66. Resources: containertypes.Resources{CPUShares: linuxMinCPUShares - 1},
  67. }
  68. daemon.adaptContainerSettings(hostConfig, true)
  69. if hostConfig.CPUShares != linuxMinCPUShares {
  70. t.Errorf("Expected CPUShares to be %d", linuxMinCPUShares)
  71. }
  72. hostConfig.CPUShares = linuxMaxCPUShares + 1
  73. daemon.adaptContainerSettings(hostConfig, true)
  74. if hostConfig.CPUShares != linuxMaxCPUShares {
  75. t.Errorf("Expected CPUShares to be %d", linuxMaxCPUShares)
  76. }
  77. hostConfig.CPUShares = 0
  78. daemon.adaptContainerSettings(hostConfig, true)
  79. if hostConfig.CPUShares != 0 {
  80. t.Error("Expected CPUShares to be unchanged")
  81. }
  82. hostConfig.CPUShares = 1024
  83. daemon.adaptContainerSettings(hostConfig, true)
  84. if hostConfig.CPUShares != 1024 {
  85. t.Error("Expected CPUShares to be unchanged")
  86. }
  87. }
  88. // Unix test as uses settings which are not available on Windows
  89. func TestAdjustCPUSharesNoAdjustment(t *testing.T) {
  90. tmp, err := ioutil.TempDir("", "docker-daemon-unix-test-")
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. defer os.RemoveAll(tmp)
  95. daemon := &Daemon{
  96. repository: tmp,
  97. root: tmp,
  98. }
  99. hostConfig := &containertypes.HostConfig{
  100. Resources: containertypes.Resources{CPUShares: linuxMinCPUShares - 1},
  101. }
  102. daemon.adaptContainerSettings(hostConfig, false)
  103. if hostConfig.CPUShares != linuxMinCPUShares-1 {
  104. t.Errorf("Expected CPUShares to be %d", linuxMinCPUShares-1)
  105. }
  106. hostConfig.CPUShares = linuxMaxCPUShares + 1
  107. daemon.adaptContainerSettings(hostConfig, false)
  108. if hostConfig.CPUShares != linuxMaxCPUShares+1 {
  109. t.Errorf("Expected CPUShares to be %d", linuxMaxCPUShares+1)
  110. }
  111. hostConfig.CPUShares = 0
  112. daemon.adaptContainerSettings(hostConfig, false)
  113. if hostConfig.CPUShares != 0 {
  114. t.Error("Expected CPUShares to be unchanged")
  115. }
  116. hostConfig.CPUShares = 1024
  117. daemon.adaptContainerSettings(hostConfig, false)
  118. if hostConfig.CPUShares != 1024 {
  119. t.Error("Expected CPUShares to be unchanged")
  120. }
  121. }
  122. // Unix test as uses settings which are not available on Windows
  123. func TestParseSecurityOptWithDeprecatedColon(t *testing.T) {
  124. ctr := &container.Container{}
  125. cfg := &containertypes.HostConfig{}
  126. // test apparmor
  127. cfg.SecurityOpt = []string{"apparmor=test_profile"}
  128. if err := parseSecurityOpt(ctr, cfg); err != nil {
  129. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  130. }
  131. if ctr.AppArmorProfile != "test_profile" {
  132. t.Fatalf("Unexpected AppArmorProfile, expected: \"test_profile\", got %q", ctr.AppArmorProfile)
  133. }
  134. // test seccomp
  135. sp := "/path/to/seccomp_test.json"
  136. cfg.SecurityOpt = []string{"seccomp=" + sp}
  137. if err := parseSecurityOpt(ctr, cfg); err != nil {
  138. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  139. }
  140. if ctr.SeccompProfile != sp {
  141. t.Fatalf("Unexpected AppArmorProfile, expected: %q, got %q", sp, ctr.SeccompProfile)
  142. }
  143. // test valid label
  144. cfg.SecurityOpt = []string{"label=user:USER"}
  145. if err := parseSecurityOpt(ctr, cfg); err != nil {
  146. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  147. }
  148. // test invalid label
  149. cfg.SecurityOpt = []string{"label"}
  150. if err := parseSecurityOpt(ctr, cfg); err == nil {
  151. t.Fatal("Expected parseSecurityOpt error, got nil")
  152. }
  153. // test invalid opt
  154. cfg.SecurityOpt = []string{"test"}
  155. if err := parseSecurityOpt(ctr, cfg); err == nil {
  156. t.Fatal("Expected parseSecurityOpt error, got nil")
  157. }
  158. }
  159. func TestParseSecurityOpt(t *testing.T) {
  160. ctr := &container.Container{}
  161. cfg := &containertypes.HostConfig{}
  162. // test apparmor
  163. cfg.SecurityOpt = []string{"apparmor=test_profile"}
  164. if err := parseSecurityOpt(ctr, cfg); err != nil {
  165. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  166. }
  167. if ctr.AppArmorProfile != "test_profile" {
  168. t.Fatalf("Unexpected AppArmorProfile, expected: \"test_profile\", got %q", ctr.AppArmorProfile)
  169. }
  170. // test seccomp
  171. sp := "/path/to/seccomp_test.json"
  172. cfg.SecurityOpt = []string{"seccomp=" + sp}
  173. if err := parseSecurityOpt(ctr, cfg); err != nil {
  174. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  175. }
  176. if ctr.SeccompProfile != sp {
  177. t.Fatalf("Unexpected SeccompProfile, expected: %q, got %q", sp, ctr.SeccompProfile)
  178. }
  179. // test valid label
  180. cfg.SecurityOpt = []string{"label=user:USER"}
  181. if err := parseSecurityOpt(ctr, cfg); err != nil {
  182. t.Fatalf("Unexpected parseSecurityOpt error: %v", err)
  183. }
  184. // test invalid label
  185. cfg.SecurityOpt = []string{"label"}
  186. if err := parseSecurityOpt(ctr, cfg); err == nil {
  187. t.Fatal("Expected parseSecurityOpt error, got nil")
  188. }
  189. // test invalid opt
  190. cfg.SecurityOpt = []string{"test"}
  191. if err := parseSecurityOpt(ctr, cfg); err == nil {
  192. t.Fatal("Expected parseSecurityOpt error, got nil")
  193. }
  194. }
  195. func TestParseNNPSecurityOptions(t *testing.T) {
  196. daemon := &Daemon{
  197. configStore: &config.Config{NoNewPrivileges: true},
  198. }
  199. ctr := &container.Container{}
  200. cfg := &containertypes.HostConfig{}
  201. // test NNP when "daemon:true" and "no-new-privileges=false""
  202. cfg.SecurityOpt = []string{"no-new-privileges=false"}
  203. if err := daemon.parseSecurityOpt(ctr, cfg); err != nil {
  204. t.Fatalf("Unexpected daemon.parseSecurityOpt error: %v", err)
  205. }
  206. if ctr.NoNewPrivileges {
  207. t.Fatalf("container.NoNewPrivileges should be FALSE: %v", ctr.NoNewPrivileges)
  208. }
  209. // test NNP when "daemon:false" and "no-new-privileges=true""
  210. daemon.configStore.NoNewPrivileges = false
  211. cfg.SecurityOpt = []string{"no-new-privileges=true"}
  212. if err := daemon.parseSecurityOpt(ctr, cfg); err != nil {
  213. t.Fatalf("Unexpected daemon.parseSecurityOpt error: %v", err)
  214. }
  215. if !ctr.NoNewPrivileges {
  216. t.Fatalf("container.NoNewPrivileges should be TRUE: %v", ctr.NoNewPrivileges)
  217. }
  218. }
  219. func TestNetworkOptions(t *testing.T) {
  220. daemon := &Daemon{}
  221. dconfigCorrect := &config.Config{
  222. CommonConfig: config.CommonConfig{
  223. ClusterStore: "consul://localhost:8500",
  224. ClusterAdvertise: "192.168.0.1:8000",
  225. },
  226. }
  227. if _, err := daemon.networkOptions(dconfigCorrect, nil, nil); err != nil {
  228. t.Fatalf("Expect networkOptions success, got error: %v", err)
  229. }
  230. dconfigWrong := &config.Config{
  231. CommonConfig: config.CommonConfig{
  232. ClusterStore: "consul://localhost:8500://test://bbb",
  233. },
  234. }
  235. if _, err := daemon.networkOptions(dconfigWrong, nil, nil); err == nil {
  236. t.Fatal("Expected networkOptions error, got nil")
  237. }
  238. }
  239. func TestVerifyPlatformContainerResources(t *testing.T) {
  240. t.Parallel()
  241. var (
  242. no = false
  243. yes = true
  244. )
  245. withMemoryLimit := func(si *sysinfo.SysInfo) {
  246. si.MemoryLimit = true
  247. }
  248. withSwapLimit := func(si *sysinfo.SysInfo) {
  249. si.SwapLimit = true
  250. }
  251. withOomKillDisable := func(si *sysinfo.SysInfo) {
  252. si.OomKillDisable = true
  253. }
  254. tests := []struct {
  255. name string
  256. resources containertypes.Resources
  257. sysInfo sysinfo.SysInfo
  258. update bool
  259. expectedWarnings []string
  260. }{
  261. {
  262. name: "no-oom-kill-disable",
  263. resources: containertypes.Resources{},
  264. sysInfo: sysInfo(t, withMemoryLimit),
  265. expectedWarnings: []string{},
  266. },
  267. {
  268. name: "oom-kill-disable-disabled",
  269. resources: containertypes.Resources{
  270. OomKillDisable: &no,
  271. },
  272. sysInfo: sysInfo(t, withMemoryLimit),
  273. expectedWarnings: []string{},
  274. },
  275. {
  276. name: "oom-kill-disable-not-supported",
  277. resources: containertypes.Resources{
  278. OomKillDisable: &yes,
  279. },
  280. sysInfo: sysInfo(t, withMemoryLimit),
  281. expectedWarnings: []string{
  282. "Your kernel does not support OomKillDisable. OomKillDisable discarded.",
  283. },
  284. },
  285. {
  286. name: "oom-kill-disable-without-memory-constraints",
  287. resources: containertypes.Resources{
  288. OomKillDisable: &yes,
  289. Memory: 0,
  290. },
  291. sysInfo: sysInfo(t, withMemoryLimit, withOomKillDisable, withSwapLimit),
  292. expectedWarnings: []string{
  293. "OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.",
  294. },
  295. },
  296. {
  297. name: "oom-kill-disable-with-memory-constraints-but-no-memory-limit-support",
  298. resources: containertypes.Resources{
  299. OomKillDisable: &yes,
  300. Memory: linuxMinMemory,
  301. },
  302. sysInfo: sysInfo(t, withOomKillDisable),
  303. expectedWarnings: []string{
  304. "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.",
  305. "OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.",
  306. },
  307. },
  308. {
  309. name: "oom-kill-disable-with-memory-constraints",
  310. resources: containertypes.Resources{
  311. OomKillDisable: &yes,
  312. Memory: linuxMinMemory,
  313. },
  314. sysInfo: sysInfo(t, withMemoryLimit, withOomKillDisable, withSwapLimit),
  315. expectedWarnings: []string{},
  316. },
  317. }
  318. for _, tc := range tests {
  319. t.Run(tc.name, func(t *testing.T) {
  320. t.Parallel()
  321. warnings, err := verifyPlatformContainerResources(&tc.resources, &tc.sysInfo, tc.update)
  322. assert.NilError(t, err)
  323. for _, w := range tc.expectedWarnings {
  324. assert.Assert(t, is.Contains(warnings, w))
  325. }
  326. })
  327. }
  328. }
  329. func sysInfo(t *testing.T, opts ...func(*sysinfo.SysInfo)) sysinfo.SysInfo {
  330. t.Helper()
  331. si := sysinfo.SysInfo{}
  332. for _, opt := range opts {
  333. opt(&si)
  334. }
  335. if si.OomKillDisable {
  336. t.Log(t.Name(), "OOM disable supported")
  337. }
  338. return si
  339. }
  340. const (
  341. // prepare major 0x1FD(509 in decimal) and minor 0x130(304)
  342. DEVNO = 0x11FD30
  343. MAJOR = 509
  344. MINOR = 304
  345. WEIGHT = 1024
  346. )
  347. func deviceTypeMock(t *testing.T, testAndCheck func(string)) {
  348. if os.Getuid() != 0 {
  349. t.Skip("root required") // for mknod
  350. }
  351. t.Parallel()
  352. tempDir, err := ioutil.TempDir("", "tempDevDir"+t.Name())
  353. assert.NilError(t, err, "create temp file")
  354. tempFile := filepath.Join(tempDir, "dev")
  355. defer os.RemoveAll(tempDir)
  356. if err = unix.Mknod(tempFile, unix.S_IFCHR, DEVNO); err != nil {
  357. t.Fatalf("mknod error %s(%x): %v", tempFile, DEVNO, err)
  358. }
  359. testAndCheck(tempFile)
  360. }
  361. func TestGetBlkioWeightDevices(t *testing.T) {
  362. deviceTypeMock(t, func(tempFile string) {
  363. mockResource := containertypes.Resources{
  364. BlkioWeightDevice: []*blkiodev.WeightDevice{{Path: tempFile, Weight: WEIGHT}},
  365. }
  366. weightDevs, err := getBlkioWeightDevices(mockResource)
  367. assert.NilError(t, err, "getBlkioWeightDevices")
  368. assert.Check(t, is.Len(weightDevs, 1), "getBlkioWeightDevices")
  369. assert.Check(t, weightDevs[0].Major == MAJOR, "get major device type")
  370. assert.Check(t, weightDevs[0].Minor == MINOR, "get minor device type")
  371. assert.Check(t, *weightDevs[0].Weight == WEIGHT, "get device weight")
  372. })
  373. }
  374. func TestGetBlkioThrottleDevices(t *testing.T) {
  375. deviceTypeMock(t, func(tempFile string) {
  376. mockDevs := []*blkiodev.ThrottleDevice{{Path: tempFile, Rate: WEIGHT}}
  377. retDevs, err := getBlkioThrottleDevices(mockDevs)
  378. assert.NilError(t, err, "getBlkioThrottleDevices")
  379. assert.Check(t, is.Len(retDevs, 1), "getBlkioThrottleDevices")
  380. assert.Check(t, retDevs[0].Major == MAJOR, "get major device type")
  381. assert.Check(t, retDevs[0].Minor == MINOR, "get minor device type")
  382. assert.Check(t, retDevs[0].Rate == WEIGHT, "get device rate")
  383. })
  384. }