daemon_unix.go 46 KB

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