daemon_unix_test.go 13 KB

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