daemon_unix.go 43 KB

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