daemon_unix.go 47 KB

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