daemon_unix.go 45 KB

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