daemon_unix.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/api/types"
  17. "github.com/docker/docker/api/types/blkiodev"
  18. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  19. containertypes "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/container"
  21. "github.com/docker/docker/image"
  22. "github.com/docker/docker/pkg/idtools"
  23. "github.com/docker/docker/pkg/parsers"
  24. "github.com/docker/docker/pkg/parsers/kernel"
  25. "github.com/docker/docker/pkg/sysinfo"
  26. "github.com/docker/docker/runconfig"
  27. runconfigopts "github.com/docker/docker/runconfig/opts"
  28. "github.com/docker/libnetwork"
  29. nwconfig "github.com/docker/libnetwork/config"
  30. "github.com/docker/libnetwork/drivers/bridge"
  31. "github.com/docker/libnetwork/netlabel"
  32. "github.com/docker/libnetwork/netutils"
  33. "github.com/docker/libnetwork/options"
  34. lntypes "github.com/docker/libnetwork/types"
  35. "github.com/golang/protobuf/ptypes"
  36. "github.com/opencontainers/runc/libcontainer/label"
  37. rsystem "github.com/opencontainers/runc/libcontainer/system"
  38. "github.com/opencontainers/runc/libcontainer/user"
  39. "github.com/opencontainers/runtime-spec/specs-go"
  40. "github.com/vishvananda/netlink"
  41. )
  42. const (
  43. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  44. linuxMinCPUShares = 2
  45. linuxMaxCPUShares = 262144
  46. platformSupported = true
  47. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  48. linuxMinMemory = 4194304
  49. // constants for remapped root settings
  50. defaultIDSpecifier string = "default"
  51. defaultRemappedID string = "dockremap"
  52. // constant for cgroup drivers
  53. cgroupFsDriver = "cgroupfs"
  54. cgroupSystemdDriver = "systemd"
  55. )
  56. func getMemoryResources(config containertypes.Resources) *specs.Memory {
  57. memory := specs.Memory{}
  58. if config.Memory > 0 {
  59. limit := uint64(config.Memory)
  60. memory.Limit = &limit
  61. }
  62. if config.MemoryReservation > 0 {
  63. reservation := uint64(config.MemoryReservation)
  64. memory.Reservation = &reservation
  65. }
  66. if config.MemorySwap != 0 {
  67. swap := uint64(config.MemorySwap)
  68. memory.Swap = &swap
  69. }
  70. if config.MemorySwappiness != nil {
  71. swappiness := uint64(*config.MemorySwappiness)
  72. memory.Swappiness = &swappiness
  73. }
  74. if config.KernelMemory != 0 {
  75. kernelMemory := uint64(config.KernelMemory)
  76. memory.Kernel = &kernelMemory
  77. }
  78. return &memory
  79. }
  80. func getCPUResources(config containertypes.Resources) *specs.CPU {
  81. cpu := specs.CPU{}
  82. if config.CPUShares != 0 {
  83. shares := uint64(config.CPUShares)
  84. cpu.Shares = &shares
  85. }
  86. if config.CpusetCpus != "" {
  87. cpuset := config.CpusetCpus
  88. cpu.Cpus = &cpuset
  89. }
  90. if config.CpusetMems != "" {
  91. cpuset := config.CpusetMems
  92. cpu.Mems = &cpuset
  93. }
  94. if config.CPUPeriod != 0 {
  95. period := uint64(config.CPUPeriod)
  96. cpu.Period = &period
  97. }
  98. if config.CPUQuota != 0 {
  99. quota := uint64(config.CPUQuota)
  100. cpu.Quota = &quota
  101. }
  102. return &cpu
  103. }
  104. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.WeightDevice, error) {
  105. var stat syscall.Stat_t
  106. var blkioWeightDevices []specs.WeightDevice
  107. for _, weightDevice := range config.BlkioWeightDevice {
  108. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  109. return nil, err
  110. }
  111. weight := weightDevice.Weight
  112. d := specs.WeightDevice{Weight: &weight}
  113. d.Major = int64(stat.Rdev / 256)
  114. d.Minor = int64(stat.Rdev % 256)
  115. blkioWeightDevices = append(blkioWeightDevices, d)
  116. }
  117. return blkioWeightDevices, nil
  118. }
  119. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  120. var (
  121. labelOpts []string
  122. err error
  123. )
  124. for _, opt := range config.SecurityOpt {
  125. if opt == "no-new-privileges" {
  126. container.NoNewPrivileges = true
  127. } else {
  128. var con []string
  129. if strings.Contains(opt, "=") {
  130. con = strings.SplitN(opt, "=", 2)
  131. } else if strings.Contains(opt, ":") {
  132. con = strings.SplitN(opt, ":", 2)
  133. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 1.13, use `=` instead.")
  134. }
  135. if len(con) != 2 {
  136. return fmt.Errorf("Invalid --security-opt 1: %q", opt)
  137. }
  138. switch con[0] {
  139. case "label":
  140. labelOpts = append(labelOpts, con[1])
  141. case "apparmor":
  142. container.AppArmorProfile = con[1]
  143. case "seccomp":
  144. container.SeccompProfile = con[1]
  145. default:
  146. return fmt.Errorf("Invalid --security-opt 2: %q", opt)
  147. }
  148. }
  149. }
  150. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  151. return err
  152. }
  153. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.ThrottleDevice, error) {
  154. var throttleDevices []specs.ThrottleDevice
  155. var stat syscall.Stat_t
  156. for _, d := range devs {
  157. if err := syscall.Stat(d.Path, &stat); err != nil {
  158. return nil, err
  159. }
  160. rate := d.Rate
  161. d := specs.ThrottleDevice{Rate: &rate}
  162. d.Major = int64(stat.Rdev / 256)
  163. d.Minor = int64(stat.Rdev % 256)
  164. throttleDevices = append(throttleDevices, d)
  165. }
  166. return throttleDevices, nil
  167. }
  168. func checkKernel() error {
  169. // Check for unsupported kernel versions
  170. // FIXME: it would be cleaner to not test for specific versions, but rather
  171. // test for specific functionalities.
  172. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  173. // without actually causing a kernel panic, so we need this workaround until
  174. // the circumstances of pre-3.10 crashes are clearer.
  175. // For details see https://github.com/docker/docker/issues/407
  176. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  177. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  178. if !kernel.CheckKernelVersion(3, 10, 0) {
  179. v, _ := kernel.GetKernelVersion()
  180. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  181. logrus.Fatalf("Your Linux kernel version %s is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.", v.String())
  182. }
  183. }
  184. return nil
  185. }
  186. // adaptContainerSettings is called during container creation to modify any
  187. // settings necessary in the HostConfig structure.
  188. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  189. if adjustCPUShares && hostConfig.CPUShares > 0 {
  190. // Handle unsupported CPUShares
  191. if hostConfig.CPUShares < linuxMinCPUShares {
  192. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  193. hostConfig.CPUShares = linuxMinCPUShares
  194. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  195. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  196. hostConfig.CPUShares = linuxMaxCPUShares
  197. }
  198. }
  199. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  200. // By default, MemorySwap is set to twice the size of Memory.
  201. hostConfig.MemorySwap = hostConfig.Memory * 2
  202. }
  203. if hostConfig.ShmSize == 0 {
  204. hostConfig.ShmSize = container.DefaultSHMSize
  205. }
  206. var err error
  207. if hostConfig.SecurityOpt == nil {
  208. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged)
  209. if err != nil {
  210. return err
  211. }
  212. }
  213. if hostConfig.MemorySwappiness == nil {
  214. defaultSwappiness := int64(-1)
  215. hostConfig.MemorySwappiness = &defaultSwappiness
  216. }
  217. if hostConfig.OomKillDisable == nil {
  218. defaultOomKillDisable := false
  219. hostConfig.OomKillDisable = &defaultOomKillDisable
  220. }
  221. return nil
  222. }
  223. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  224. warnings := []string{}
  225. // memory subsystem checks and adjustments
  226. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  227. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  228. }
  229. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  230. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  231. logrus.Warn("Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  232. resources.Memory = 0
  233. resources.MemorySwap = -1
  234. }
  235. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  236. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  237. logrus.Warn("Your kernel does not support swap limit capabilities,or the cgroup is not mounted. Memory limited without swap.")
  238. resources.MemorySwap = -1
  239. }
  240. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  241. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  242. }
  243. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  244. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  245. }
  246. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  247. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  248. logrus.Warn("Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.")
  249. resources.MemorySwappiness = nil
  250. }
  251. if resources.MemorySwappiness != nil {
  252. swappiness := *resources.MemorySwappiness
  253. if swappiness < -1 || swappiness > 100 {
  254. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  255. }
  256. }
  257. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  258. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  259. logrus.Warn("Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  260. resources.MemoryReservation = 0
  261. }
  262. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  263. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  264. }
  265. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  266. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  267. }
  268. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  269. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  270. logrus.Warn("Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  271. resources.KernelMemory = 0
  272. }
  273. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  274. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  275. }
  276. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  277. warnings = append(warnings, "You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  278. logrus.Warn("You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  279. }
  280. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  281. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  282. // warning the caller if they already wanted the feature to be off
  283. if *resources.OomKillDisable {
  284. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  285. logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  286. }
  287. resources.OomKillDisable = nil
  288. }
  289. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  290. warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  291. logrus.Warn("Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  292. resources.PidsLimit = 0
  293. }
  294. // cpu subsystem checks and adjustments
  295. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  296. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  297. logrus.Warn("Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  298. resources.CPUShares = 0
  299. }
  300. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  301. warnings = append(warnings, "Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  302. logrus.Warn("Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  303. resources.CPUPeriod = 0
  304. }
  305. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  306. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  307. }
  308. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  309. warnings = append(warnings, "Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  310. logrus.Warn("Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  311. resources.CPUQuota = 0
  312. }
  313. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  314. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  315. }
  316. if resources.CPUPercent > 0 {
  317. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  318. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  319. resources.CPUPercent = 0
  320. }
  321. // cpuset subsystem checks and adjustments
  322. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  323. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  324. logrus.Warn("Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  325. resources.CpusetCpus = ""
  326. resources.CpusetMems = ""
  327. }
  328. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  329. if err != nil {
  330. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  331. }
  332. if !cpusAvailable {
  333. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  334. }
  335. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  336. if err != nil {
  337. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  338. }
  339. if !memsAvailable {
  340. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  341. }
  342. // blkio subsystem checks and adjustments
  343. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  344. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  345. logrus.Warn("Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  346. resources.BlkioWeight = 0
  347. }
  348. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  349. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  350. }
  351. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  352. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  353. }
  354. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  355. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  356. logrus.Warn("Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  357. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  358. }
  359. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  360. warnings = append(warnings, "Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded.")
  361. logrus.Warn("Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded")
  362. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  363. }
  364. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  365. warnings = append(warnings, "Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  366. logrus.Warn("Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  367. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  368. }
  369. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  370. warnings = append(warnings, "Your kernel does not support IOPS Block read limit or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  371. logrus.Warn("Your kernel does not support IOPS Block I/O read limit in IO or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  372. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  373. }
  374. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  375. warnings = append(warnings, "Your kernel does not support IOPS Block write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  376. logrus.Warn("Your kernel does not support IOPS Block I/O write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  377. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  378. }
  379. return warnings, nil
  380. }
  381. func (daemon *Daemon) getCgroupDriver() string {
  382. cgroupDriver := cgroupFsDriver
  383. if UsingSystemd(daemon.configStore) {
  384. cgroupDriver = cgroupSystemdDriver
  385. }
  386. return cgroupDriver
  387. }
  388. // getCD gets the raw value of the native.cgroupdriver option, if set.
  389. func getCD(config *Config) string {
  390. for _, option := range config.ExecOptions {
  391. key, val, err := parsers.ParseKeyValueOpt(option)
  392. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  393. continue
  394. }
  395. return val
  396. }
  397. return ""
  398. }
  399. // VerifyCgroupDriver validates native.cgroupdriver
  400. func VerifyCgroupDriver(config *Config) error {
  401. cd := getCD(config)
  402. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  403. return nil
  404. }
  405. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  406. }
  407. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  408. func UsingSystemd(config *Config) bool {
  409. return getCD(config) == cgroupSystemdDriver
  410. }
  411. // verifyPlatformContainerSettings performs platform-specific validation of the
  412. // hostconfig and config structures.
  413. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  414. warnings := []string{}
  415. sysInfo := sysinfo.New(true)
  416. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  417. if err != nil {
  418. return warnings, err
  419. }
  420. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  421. // no matter err is nil or not, w could have data in itself.
  422. warnings = append(warnings, w...)
  423. if err != nil {
  424. return warnings, err
  425. }
  426. if hostConfig.ShmSize < 0 {
  427. return warnings, fmt.Errorf("SHM size can not be less than 0")
  428. }
  429. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  430. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  431. }
  432. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  433. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  434. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  435. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  436. }
  437. // check for various conflicting options with user namespaces
  438. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  439. if hostConfig.Privileged {
  440. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  441. }
  442. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  443. return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
  444. }
  445. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  446. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  447. }
  448. }
  449. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  450. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  451. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  452. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  453. }
  454. }
  455. if hostConfig.Runtime == "" {
  456. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  457. }
  458. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  459. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  460. }
  461. return warnings, nil
  462. }
  463. // platformReload update configuration with platform specific options
  464. func (daemon *Daemon) platformReload(config *Config) map[string]string {
  465. if config.IsValueSet("runtimes") {
  466. daemon.configStore.Runtimes = config.Runtimes
  467. // Always set the default one
  468. daemon.configStore.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  469. }
  470. if config.DefaultRuntime != "" {
  471. daemon.configStore.DefaultRuntime = config.DefaultRuntime
  472. }
  473. // Update attributes
  474. var runtimeList bytes.Buffer
  475. for name, rt := range daemon.configStore.Runtimes {
  476. if runtimeList.Len() > 0 {
  477. runtimeList.WriteRune(' ')
  478. }
  479. runtimeList.WriteString(fmt.Sprintf("%s:%s", name, rt))
  480. }
  481. return map[string]string{
  482. "runtimes": runtimeList.String(),
  483. "default-runtime": daemon.configStore.DefaultRuntime,
  484. }
  485. }
  486. // verifyDaemonSettings performs validation of daemon config struct
  487. func verifyDaemonSettings(config *Config) error {
  488. // Check for mutually incompatible config options
  489. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  490. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  491. }
  492. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  493. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  494. }
  495. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  496. config.bridgeConfig.EnableIPMasq = false
  497. }
  498. if err := VerifyCgroupDriver(config); err != nil {
  499. return err
  500. }
  501. if config.CgroupParent != "" && UsingSystemd(config) {
  502. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  503. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  504. }
  505. }
  506. if config.DefaultRuntime == "" {
  507. config.DefaultRuntime = stockRuntimeName
  508. }
  509. if config.Runtimes == nil {
  510. config.Runtimes = make(map[string]types.Runtime)
  511. }
  512. config.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  513. return nil
  514. }
  515. // checkSystem validates platform-specific requirements
  516. func checkSystem() error {
  517. if os.Geteuid() != 0 {
  518. return fmt.Errorf("The Docker daemon needs to be run as root")
  519. }
  520. return checkKernel()
  521. }
  522. // configureMaxThreads sets the Go runtime max threads threshold
  523. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  524. func configureMaxThreads(config *Config) error {
  525. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  526. if err != nil {
  527. return err
  528. }
  529. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  530. if err != nil {
  531. return err
  532. }
  533. maxThreads := (mtint / 100) * 90
  534. debug.SetMaxThreads(maxThreads)
  535. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  536. return nil
  537. }
  538. // configureKernelSecuritySupport configures and validates security support for the kernel
  539. func configureKernelSecuritySupport(config *Config, driverName string) error {
  540. if config.EnableSelinuxSupport {
  541. if !selinuxEnabled() {
  542. logrus.Warn("Docker could not enable SELinux on the host system")
  543. }
  544. } else {
  545. selinuxSetDisabled()
  546. }
  547. return nil
  548. }
  549. func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  550. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  551. if err != nil {
  552. return nil, err
  553. }
  554. controller, err := libnetwork.New(netOptions...)
  555. if err != nil {
  556. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  557. }
  558. if len(activeSandboxes) > 0 {
  559. logrus.Infof("There are old running containers, the network config will not take affect")
  560. return controller, nil
  561. }
  562. // Initialize default network on "null"
  563. if n, _ := controller.NetworkByName("none"); n == nil {
  564. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  565. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  566. }
  567. }
  568. // Initialize default network on "host"
  569. if n, _ := controller.NetworkByName("host"); n == nil {
  570. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  571. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  572. }
  573. }
  574. // Clear stale bridge network
  575. if n, err := controller.NetworkByName("bridge"); err == nil {
  576. if err = n.Delete(); err != nil {
  577. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  578. }
  579. }
  580. if !config.DisableBridge {
  581. // Initialize default driver "bridge"
  582. if err := initBridgeDriver(controller, config); err != nil {
  583. return nil, err
  584. }
  585. } else {
  586. removeDefaultBridgeInterface()
  587. }
  588. return controller, nil
  589. }
  590. func driverOptions(config *Config) []nwconfig.Option {
  591. bridgeConfig := options.Generic{
  592. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  593. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  594. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy,
  595. "UserlandProxyPath": config.bridgeConfig.UserlandProxyPath}
  596. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  597. dOptions := []nwconfig.Option{}
  598. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  599. return dOptions
  600. }
  601. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  602. bridgeName := bridge.DefaultBridgeName
  603. if config.bridgeConfig.Iface != "" {
  604. bridgeName = config.bridgeConfig.Iface
  605. }
  606. netOption := map[string]string{
  607. bridge.BridgeName: bridgeName,
  608. bridge.DefaultBridge: strconv.FormatBool(true),
  609. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  610. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  611. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  612. }
  613. // --ip processing
  614. if config.bridgeConfig.DefaultIP != nil {
  615. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  616. }
  617. var (
  618. ipamV4Conf *libnetwork.IpamConf
  619. ipamV6Conf *libnetwork.IpamConf
  620. )
  621. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  622. nw, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  623. if err == nil {
  624. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  625. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  626. if hip.IsGlobalUnicast() {
  627. ipamV4Conf.Gateway = nw.IP.String()
  628. }
  629. }
  630. if config.bridgeConfig.IP != "" {
  631. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  632. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  633. if err != nil {
  634. return err
  635. }
  636. ipamV4Conf.Gateway = ip.String()
  637. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  638. logrus.Infof("Default bridge (%s) is assigned with an IP address %s. Daemon option --bip can be used to set a preferred IP address", bridgeName, ipamV4Conf.PreferredPool)
  639. }
  640. if config.bridgeConfig.FixedCIDR != "" {
  641. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  642. if err != nil {
  643. return err
  644. }
  645. ipamV4Conf.SubPool = fCIDR.String()
  646. }
  647. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  648. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  649. }
  650. var deferIPv6Alloc bool
  651. if config.bridgeConfig.FixedCIDRv6 != "" {
  652. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  653. if err != nil {
  654. return err
  655. }
  656. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  657. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  658. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  659. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  660. // on this network until after the driver has created the endpoint and returned the
  661. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  662. ones, _ := fCIDRv6.Mask.Size()
  663. deferIPv6Alloc = ones <= 80
  664. if ipamV6Conf == nil {
  665. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  666. }
  667. ipamV6Conf.PreferredPool = fCIDRv6.String()
  668. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  669. // address belongs to the same network, we need to inform libnetwork about it, so
  670. // that it can be reserved with IPAM and it will not be given away to somebody else
  671. for _, nw6 := range nw6List {
  672. if fCIDRv6.Contains(nw6.IP) {
  673. ipamV6Conf.Gateway = nw6.IP.String()
  674. break
  675. }
  676. }
  677. }
  678. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  679. if ipamV6Conf == nil {
  680. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  681. }
  682. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  683. }
  684. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  685. v6Conf := []*libnetwork.IpamConf{}
  686. if ipamV6Conf != nil {
  687. v6Conf = append(v6Conf, ipamV6Conf)
  688. }
  689. // Initialize default network on "bridge" with the same name
  690. _, err = controller.NewNetwork("bridge", "bridge", "",
  691. libnetwork.NetworkOptionEnableIPv6(config.bridgeConfig.EnableIPv6),
  692. libnetwork.NetworkOptionDriverOpts(netOption),
  693. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  694. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  695. if err != nil {
  696. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  697. }
  698. return nil
  699. }
  700. // Remove default bridge interface if present (--bridge=none use case)
  701. func removeDefaultBridgeInterface() {
  702. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  703. if err := netlink.LinkDel(lnk); err != nil {
  704. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  705. }
  706. }
  707. }
  708. func (daemon *Daemon) getLayerInit() func(string) error {
  709. return daemon.setupInitLayer
  710. }
  711. // setupInitLayer populates a directory with mountpoints suitable
  712. // for bind-mounting things into the container.
  713. //
  714. // This extra layer is used by all containers as the top-most ro layer. It protects
  715. // the container from unwanted side-effects on the rw layer.
  716. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  717. for pth, typ := range map[string]string{
  718. "/dev/pts": "dir",
  719. "/dev/shm": "dir",
  720. "/proc": "dir",
  721. "/sys": "dir",
  722. "/.dockerenv": "file",
  723. "/etc/resolv.conf": "file",
  724. "/etc/hosts": "file",
  725. "/etc/hostname": "file",
  726. "/dev/console": "file",
  727. "/etc/mtab": "/proc/mounts",
  728. } {
  729. parts := strings.Split(pth, "/")
  730. prev := "/"
  731. for _, p := range parts[1:] {
  732. prev = filepath.Join(prev, p)
  733. syscall.Unlink(filepath.Join(initLayer, prev))
  734. }
  735. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  736. if os.IsNotExist(err) {
  737. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  738. return err
  739. }
  740. switch typ {
  741. case "dir":
  742. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  743. return err
  744. }
  745. case "file":
  746. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  747. if err != nil {
  748. return err
  749. }
  750. f.Chown(rootUID, rootGID)
  751. f.Close()
  752. default:
  753. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  754. return err
  755. }
  756. }
  757. } else {
  758. return err
  759. }
  760. }
  761. }
  762. // Layer is ready to use, if it wasn't before.
  763. return nil
  764. }
  765. // Parse the remapped root (user namespace) option, which can be one of:
  766. // username - valid username from /etc/passwd
  767. // username:groupname - valid username; valid groupname from /etc/group
  768. // uid - 32-bit unsigned int valid Linux UID value
  769. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  770. //
  771. // If no groupname is specified, and a username is specified, an attempt
  772. // will be made to lookup a gid for that username as a groupname
  773. //
  774. // If names are used, they are verified to exist in passwd/group
  775. func parseRemappedRoot(usergrp string) (string, string, error) {
  776. var (
  777. userID, groupID int
  778. username, groupname string
  779. )
  780. idparts := strings.Split(usergrp, ":")
  781. if len(idparts) > 2 {
  782. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  783. }
  784. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  785. // must be a uid; take it as valid
  786. userID = int(uid)
  787. luser, err := user.LookupUid(userID)
  788. if err != nil {
  789. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  790. }
  791. username = luser.Name
  792. if len(idparts) == 1 {
  793. // if the uid was numeric and no gid was specified, take the uid as the gid
  794. groupID = userID
  795. lgrp, err := user.LookupGid(groupID)
  796. if err != nil {
  797. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  798. }
  799. groupname = lgrp.Name
  800. }
  801. } else {
  802. lookupName := idparts[0]
  803. // special case: if the user specified "default", they want Docker to create or
  804. // use (after creation) the "dockremap" user/group for root remapping
  805. if lookupName == defaultIDSpecifier {
  806. lookupName = defaultRemappedID
  807. }
  808. luser, err := user.LookupUser(lookupName)
  809. if err != nil && idparts[0] != defaultIDSpecifier {
  810. // error if the name requested isn't the special "dockremap" ID
  811. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  812. } else if err != nil {
  813. // special case-- if the username == "default", then we have been asked
  814. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  815. // ranges will be used for the user and group mappings in user namespaced containers
  816. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  817. if err == nil {
  818. return defaultRemappedID, defaultRemappedID, nil
  819. }
  820. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  821. }
  822. username = luser.Name
  823. if len(idparts) == 1 {
  824. // we only have a string username, and no group specified; look up gid from username as group
  825. group, err := user.LookupGroup(lookupName)
  826. if err != nil {
  827. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  828. }
  829. groupID = group.Gid
  830. groupname = group.Name
  831. }
  832. }
  833. if len(idparts) == 2 {
  834. // groupname or gid is separately specified and must be resolved
  835. // to an unsigned 32-bit gid
  836. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  837. // must be a gid, take it as valid
  838. groupID = int(gid)
  839. lgrp, err := user.LookupGid(groupID)
  840. if err != nil {
  841. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  842. }
  843. groupname = lgrp.Name
  844. } else {
  845. // not a number; attempt a lookup
  846. if _, err := user.LookupGroup(idparts[1]); err != nil {
  847. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  848. }
  849. groupname = idparts[1]
  850. }
  851. }
  852. return username, groupname, nil
  853. }
  854. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  855. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  856. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  857. }
  858. // if the daemon was started with remapped root option, parse
  859. // the config option to the int uid,gid values
  860. var (
  861. uidMaps, gidMaps []idtools.IDMap
  862. )
  863. if config.RemappedRoot != "" {
  864. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  865. if err != nil {
  866. return nil, nil, err
  867. }
  868. if username == "root" {
  869. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  870. // effectively
  871. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  872. return uidMaps, gidMaps, nil
  873. }
  874. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  875. // update remapped root setting now that we have resolved them to actual names
  876. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  877. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  878. if err != nil {
  879. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  880. }
  881. }
  882. return uidMaps, gidMaps, nil
  883. }
  884. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  885. config.Root = rootDir
  886. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  887. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  888. // (e.g. mounted layers of a container) can traverse this path.
  889. // The user namespace support will create subdirectories for the remapped root host uid:gid
  890. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  891. // layer content subtrees.
  892. if _, err := os.Stat(rootDir); err == nil {
  893. // root current exists; verify the access bits are correct by setting them
  894. if err = os.Chmod(rootDir, 0711); err != nil {
  895. return err
  896. }
  897. } else if os.IsNotExist(err) {
  898. // no root exists yet, create it 0711 with root:root ownership
  899. if err := os.MkdirAll(rootDir, 0711); err != nil {
  900. return err
  901. }
  902. }
  903. // if user namespaces are enabled we will create a subtree underneath the specified root
  904. // with any/all specified remapped root uid/gid options on the daemon creating
  905. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  906. // `chdir()` to work for containers namespaced to that uid/gid)
  907. if config.RemappedRoot != "" {
  908. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  909. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  910. // Create the root directory if it doesn't exist
  911. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  912. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  913. }
  914. // we also need to verify that any pre-existing directories in the path to
  915. // the graphroot won't block access to remapped root--if any pre-existing directory
  916. // has strict permissions that don't allow "x", container start will fail, so
  917. // better to warn and fail now
  918. dirPath := config.Root
  919. for {
  920. dirPath = filepath.Dir(dirPath)
  921. if dirPath == "/" {
  922. break
  923. }
  924. if !idtools.CanAccess(dirPath, rootUID, rootGID) {
  925. return fmt.Errorf("A subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories.", config.Root)
  926. }
  927. }
  928. }
  929. return nil
  930. }
  931. // registerLinks writes the links to a file.
  932. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  933. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  934. return nil
  935. }
  936. for _, l := range hostConfig.Links {
  937. name, alias, err := runconfigopts.ParseLink(l)
  938. if err != nil {
  939. return err
  940. }
  941. child, err := daemon.GetContainer(name)
  942. if err != nil {
  943. return fmt.Errorf("Could not get container for %s", name)
  944. }
  945. for child.HostConfig.NetworkMode.IsContainer() {
  946. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  947. child, err = daemon.GetContainer(parts[1])
  948. if err != nil {
  949. return fmt.Errorf("Could not get container for %s", parts[1])
  950. }
  951. }
  952. if child.HostConfig.NetworkMode.IsHost() {
  953. return runconfig.ErrConflictHostNetworkAndLinks
  954. }
  955. if err := daemon.registerLink(container, child, alias); err != nil {
  956. return err
  957. }
  958. }
  959. // After we load all the links into the daemon
  960. // set them to nil on the hostconfig
  961. return container.WriteHostConfig()
  962. }
  963. // conditionalMountOnStart is a platform specific helper function during the
  964. // container start to call mount.
  965. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  966. return daemon.Mount(container)
  967. }
  968. // conditionalUnmountOnCleanup is a platform specific helper function called
  969. // during the cleanup of a container to unmount.
  970. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  971. return daemon.Unmount(container)
  972. }
  973. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  974. if !c.IsRunning() {
  975. return nil, errNotRunning{c.ID}
  976. }
  977. stats, err := daemon.containerd.Stats(c.ID)
  978. if err != nil {
  979. return nil, err
  980. }
  981. s := &types.StatsJSON{}
  982. cgs := stats.CgroupStats
  983. if cgs != nil {
  984. s.BlkioStats = types.BlkioStats{
  985. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  986. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  987. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  988. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  989. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  990. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  991. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  992. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  993. }
  994. cpu := cgs.CpuStats
  995. s.CPUStats = types.CPUStats{
  996. CPUUsage: types.CPUUsage{
  997. TotalUsage: cpu.CpuUsage.TotalUsage,
  998. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  999. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  1000. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  1001. },
  1002. ThrottlingData: types.ThrottlingData{
  1003. Periods: cpu.ThrottlingData.Periods,
  1004. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  1005. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  1006. },
  1007. }
  1008. mem := cgs.MemoryStats.Usage
  1009. s.MemoryStats = types.MemoryStats{
  1010. Usage: mem.Usage,
  1011. MaxUsage: mem.MaxUsage,
  1012. Stats: cgs.MemoryStats.Stats,
  1013. Failcnt: mem.Failcnt,
  1014. Limit: mem.Limit,
  1015. }
  1016. // if the container does not set memory limit, use the machineMemory
  1017. if mem.Limit > daemon.statsCollector.machineMemory && daemon.statsCollector.machineMemory > 0 {
  1018. s.MemoryStats.Limit = daemon.statsCollector.machineMemory
  1019. }
  1020. if cgs.PidsStats != nil {
  1021. s.PidsStats = types.PidsStats{
  1022. Current: cgs.PidsStats.Current,
  1023. }
  1024. }
  1025. }
  1026. s.Read, err = ptypes.Timestamp(stats.Timestamp)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. return s, nil
  1031. }
  1032. // setDefaultIsolation determines the default isolation mode for the
  1033. // daemon to run in. This is only applicable on Windows
  1034. func (daemon *Daemon) setDefaultIsolation() error {
  1035. return nil
  1036. }
  1037. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1038. var layers []string
  1039. for _, l := range rootfs.DiffIDs {
  1040. layers = append(layers, l.String())
  1041. }
  1042. return types.RootFS{
  1043. Type: rootfs.Type,
  1044. Layers: layers,
  1045. }
  1046. }
  1047. // setupDaemonProcess sets various settings for the daemon's process
  1048. func setupDaemonProcess(config *Config) error {
  1049. // setup the daemons oom_score_adj
  1050. return setupOOMScoreAdj(config.OOMScoreAdjust)
  1051. }
  1052. func setupOOMScoreAdj(score int) error {
  1053. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1054. if err != nil {
  1055. return err
  1056. }
  1057. stringScore := strconv.Itoa(score)
  1058. _, err = f.WriteString(stringScore)
  1059. if os.IsPermission(err) {
  1060. // Setting oom_score_adj does not work in an
  1061. // unprivileged container. Ignore the error, but log
  1062. // it if we appear not to be in that situation.
  1063. if !rsystem.RunningInUserNS() {
  1064. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1065. }
  1066. return nil
  1067. }
  1068. f.Close()
  1069. return err
  1070. }