daemon_unix.go 47 KB

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