daemon_unix.go 43 KB

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