daemon_unix.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/api/types/blkiodev"
  19. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  20. containertypes "github.com/docker/docker/api/types/container"
  21. "github.com/docker/docker/container"
  22. "github.com/docker/docker/image"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/idtools"
  25. "github.com/docker/docker/pkg/parsers"
  26. "github.com/docker/docker/pkg/parsers/kernel"
  27. "github.com/docker/docker/pkg/sysinfo"
  28. "github.com/docker/docker/runconfig"
  29. "github.com/docker/docker/volume"
  30. "github.com/docker/libnetwork"
  31. nwconfig "github.com/docker/libnetwork/config"
  32. "github.com/docker/libnetwork/drivers/bridge"
  33. "github.com/docker/libnetwork/netlabel"
  34. "github.com/docker/libnetwork/netutils"
  35. "github.com/docker/libnetwork/options"
  36. lntypes "github.com/docker/libnetwork/types"
  37. "github.com/golang/protobuf/ptypes"
  38. "github.com/opencontainers/runc/libcontainer/cgroups"
  39. "github.com/opencontainers/runc/libcontainer/label"
  40. rsystem "github.com/opencontainers/runc/libcontainer/system"
  41. specs "github.com/opencontainers/runtime-spec/specs-go"
  42. "github.com/pkg/errors"
  43. "github.com/vishvananda/netlink"
  44. )
  45. const (
  46. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  47. linuxMinCPUShares = 2
  48. linuxMaxCPUShares = 262144
  49. platformSupported = true
  50. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  51. linuxMinMemory = 4194304
  52. // constants for remapped root settings
  53. defaultIDSpecifier string = "default"
  54. defaultRemappedID string = "dockremap"
  55. // constant for cgroup drivers
  56. cgroupFsDriver = "cgroupfs"
  57. cgroupSystemdDriver = "systemd"
  58. )
  59. func getMemoryResources(config containertypes.Resources) *specs.Memory {
  60. memory := specs.Memory{}
  61. if config.Memory > 0 {
  62. limit := uint64(config.Memory)
  63. memory.Limit = &limit
  64. }
  65. if config.MemoryReservation > 0 {
  66. reservation := uint64(config.MemoryReservation)
  67. memory.Reservation = &reservation
  68. }
  69. if config.MemorySwap != 0 {
  70. swap := uint64(config.MemorySwap)
  71. memory.Swap = &swap
  72. }
  73. if config.MemorySwappiness != nil {
  74. swappiness := uint64(*config.MemorySwappiness)
  75. memory.Swappiness = &swappiness
  76. }
  77. if config.KernelMemory != 0 {
  78. kernelMemory := uint64(config.KernelMemory)
  79. memory.Kernel = &kernelMemory
  80. }
  81. return &memory
  82. }
  83. func getCPUResources(config containertypes.Resources) *specs.CPU {
  84. cpu := specs.CPU{}
  85. if config.CPUShares != 0 {
  86. shares := uint64(config.CPUShares)
  87. cpu.Shares = &shares
  88. }
  89. if config.CpusetCpus != "" {
  90. cpuset := config.CpusetCpus
  91. cpu.Cpus = &cpuset
  92. }
  93. if config.CpusetMems != "" {
  94. cpuset := config.CpusetMems
  95. cpu.Mems = &cpuset
  96. }
  97. if config.NanoCPUs > 0 {
  98. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  99. period := uint64(100 * time.Millisecond / time.Microsecond)
  100. quota := uint64(config.NanoCPUs) * period / 1e9
  101. cpu.Period = &period
  102. cpu.Quota = &quota
  103. }
  104. if config.CPUPeriod != 0 {
  105. period := uint64(config.CPUPeriod)
  106. cpu.Period = &period
  107. }
  108. if config.CPUQuota != 0 {
  109. quota := uint64(config.CPUQuota)
  110. cpu.Quota = &quota
  111. }
  112. if config.CPURealtimePeriod != 0 {
  113. period := uint64(config.CPURealtimePeriod)
  114. cpu.RealtimePeriod = &period
  115. }
  116. if config.CPURealtimeRuntime != 0 {
  117. runtime := uint64(config.CPURealtimeRuntime)
  118. cpu.RealtimeRuntime = &runtime
  119. }
  120. return &cpu
  121. }
  122. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.WeightDevice, error) {
  123. var stat syscall.Stat_t
  124. var blkioWeightDevices []specs.WeightDevice
  125. for _, weightDevice := range config.BlkioWeightDevice {
  126. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  127. return nil, err
  128. }
  129. weight := weightDevice.Weight
  130. d := specs.WeightDevice{Weight: &weight}
  131. d.Major = int64(stat.Rdev / 256)
  132. d.Minor = int64(stat.Rdev % 256)
  133. blkioWeightDevices = append(blkioWeightDevices, d)
  134. }
  135. return blkioWeightDevices, nil
  136. }
  137. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  138. var (
  139. labelOpts []string
  140. err error
  141. )
  142. for _, opt := range config.SecurityOpt {
  143. if opt == "no-new-privileges" {
  144. container.NoNewPrivileges = true
  145. continue
  146. }
  147. var con []string
  148. if strings.Contains(opt, "=") {
  149. con = strings.SplitN(opt, "=", 2)
  150. } else if strings.Contains(opt, ":") {
  151. con = strings.SplitN(opt, ":", 2)
  152. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 1.14, use `=` instead.")
  153. }
  154. if len(con) != 2 {
  155. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  156. }
  157. switch con[0] {
  158. case "label":
  159. labelOpts = append(labelOpts, con[1])
  160. case "apparmor":
  161. container.AppArmorProfile = con[1]
  162. case "seccomp":
  163. container.SeccompProfile = con[1]
  164. default:
  165. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  166. }
  167. }
  168. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  169. return err
  170. }
  171. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.ThrottleDevice, error) {
  172. var throttleDevices []specs.ThrottleDevice
  173. var stat syscall.Stat_t
  174. for _, d := range devs {
  175. if err := syscall.Stat(d.Path, &stat); err != nil {
  176. return nil, err
  177. }
  178. rate := d.Rate
  179. d := specs.ThrottleDevice{Rate: &rate}
  180. d.Major = int64(stat.Rdev / 256)
  181. d.Minor = int64(stat.Rdev % 256)
  182. throttleDevices = append(throttleDevices, d)
  183. }
  184. return throttleDevices, nil
  185. }
  186. func checkKernel() error {
  187. // Check for unsupported kernel versions
  188. // FIXME: it would be cleaner to not test for specific versions, but rather
  189. // test for specific functionalities.
  190. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  191. // without actually causing a kernel panic, so we need this workaround until
  192. // the circumstances of pre-3.10 crashes are clearer.
  193. // For details see https://github.com/docker/docker/issues/407
  194. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  195. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  196. if !kernel.CheckKernelVersion(3, 10, 0) {
  197. v, _ := kernel.GetKernelVersion()
  198. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  199. 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())
  200. }
  201. }
  202. return nil
  203. }
  204. // adaptContainerSettings is called during container creation to modify any
  205. // settings necessary in the HostConfig structure.
  206. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  207. if adjustCPUShares && hostConfig.CPUShares > 0 {
  208. // Handle unsupported CPUShares
  209. if hostConfig.CPUShares < linuxMinCPUShares {
  210. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  211. hostConfig.CPUShares = linuxMinCPUShares
  212. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  213. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  214. hostConfig.CPUShares = linuxMaxCPUShares
  215. }
  216. }
  217. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  218. // By default, MemorySwap is set to twice the size of Memory.
  219. hostConfig.MemorySwap = hostConfig.Memory * 2
  220. }
  221. if hostConfig.ShmSize == 0 {
  222. hostConfig.ShmSize = defaultShmSize
  223. if daemon.configStore != nil {
  224. hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
  225. }
  226. }
  227. var err error
  228. opts, err := daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged)
  229. if err != nil {
  230. return err
  231. }
  232. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, opts...)
  233. if hostConfig.MemorySwappiness == nil {
  234. defaultSwappiness := int64(-1)
  235. hostConfig.MemorySwappiness = &defaultSwappiness
  236. }
  237. if hostConfig.OomKillDisable == nil {
  238. defaultOomKillDisable := false
  239. hostConfig.OomKillDisable = &defaultOomKillDisable
  240. }
  241. return nil
  242. }
  243. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  244. warnings := []string{}
  245. // memory subsystem checks and adjustments
  246. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  247. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  248. }
  249. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  250. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  251. logrus.Warn("Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  252. resources.Memory = 0
  253. resources.MemorySwap = -1
  254. }
  255. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  256. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  257. logrus.Warn("Your kernel does not support swap limit capabilities,or the cgroup is not mounted. Memory limited without swap.")
  258. resources.MemorySwap = -1
  259. }
  260. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  261. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  262. }
  263. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  264. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  265. }
  266. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  267. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  268. logrus.Warn("Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.")
  269. resources.MemorySwappiness = nil
  270. }
  271. if resources.MemorySwappiness != nil {
  272. swappiness := *resources.MemorySwappiness
  273. if swappiness < -1 || swappiness > 100 {
  274. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  275. }
  276. }
  277. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  278. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  279. logrus.Warn("Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  280. resources.MemoryReservation = 0
  281. }
  282. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  283. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  284. }
  285. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  286. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  287. }
  288. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  289. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  290. logrus.Warn("Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  291. resources.KernelMemory = 0
  292. }
  293. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  294. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  295. }
  296. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  297. 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.")
  298. 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.")
  299. }
  300. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  301. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  302. // warning the caller if they already wanted the feature to be off
  303. if *resources.OomKillDisable {
  304. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  305. logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  306. }
  307. resources.OomKillDisable = nil
  308. }
  309. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  310. warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  311. logrus.Warn("Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  312. resources.PidsLimit = 0
  313. }
  314. // cpu subsystem checks and adjustments
  315. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  316. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  317. }
  318. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  319. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  320. }
  321. if resources.NanoCPUs > 0 && (!sysInfo.CPUCfsPeriod || !sysInfo.CPUCfsQuota) {
  322. return warnings, fmt.Errorf("NanoCPUs can not be set, as your kernel does not support CPU cfs period/quota or the cgroup is not mounted")
  323. }
  324. // The highest precision we could get on Linux is 0.001, by setting
  325. // cpu.cfs_period_us=1000ms
  326. // cpu.cfs_quota=1ms
  327. // See the following link for details:
  328. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  329. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  330. // The error message is 0.01 so that this is consistent with Windows
  331. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  332. return warnings, fmt.Errorf("Range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU())
  333. }
  334. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  335. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  336. logrus.Warn("Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  337. resources.CPUShares = 0
  338. }
  339. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  340. warnings = append(warnings, "Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  341. logrus.Warn("Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  342. resources.CPUPeriod = 0
  343. }
  344. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  345. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  346. }
  347. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  348. warnings = append(warnings, "Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  349. logrus.Warn("Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  350. resources.CPUQuota = 0
  351. }
  352. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  353. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  354. }
  355. if resources.CPUPercent > 0 {
  356. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  357. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  358. resources.CPUPercent = 0
  359. }
  360. // cpuset subsystem checks and adjustments
  361. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  362. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  363. logrus.Warn("Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  364. resources.CpusetCpus = ""
  365. resources.CpusetMems = ""
  366. }
  367. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  368. if err != nil {
  369. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  370. }
  371. if !cpusAvailable {
  372. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  373. }
  374. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  375. if err != nil {
  376. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  377. }
  378. if !memsAvailable {
  379. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  380. }
  381. // blkio subsystem checks and adjustments
  382. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  383. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  384. logrus.Warn("Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  385. resources.BlkioWeight = 0
  386. }
  387. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  388. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  389. }
  390. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  391. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  392. }
  393. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  394. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  395. logrus.Warn("Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  396. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  397. }
  398. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  399. 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.")
  400. 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")
  401. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  402. }
  403. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  404. 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.")
  405. 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.")
  406. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  407. }
  408. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  409. 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.")
  410. 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.")
  411. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  412. }
  413. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  414. 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.")
  415. 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.")
  416. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  417. }
  418. return warnings, nil
  419. }
  420. func (daemon *Daemon) getCgroupDriver() string {
  421. cgroupDriver := cgroupFsDriver
  422. if UsingSystemd(daemon.configStore) {
  423. cgroupDriver = cgroupSystemdDriver
  424. }
  425. return cgroupDriver
  426. }
  427. // getCD gets the raw value of the native.cgroupdriver option, if set.
  428. func getCD(config *Config) string {
  429. for _, option := range config.ExecOptions {
  430. key, val, err := parsers.ParseKeyValueOpt(option)
  431. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  432. continue
  433. }
  434. return val
  435. }
  436. return ""
  437. }
  438. // VerifyCgroupDriver validates native.cgroupdriver
  439. func VerifyCgroupDriver(config *Config) error {
  440. cd := getCD(config)
  441. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  442. return nil
  443. }
  444. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  445. }
  446. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  447. func UsingSystemd(config *Config) bool {
  448. return getCD(config) == cgroupSystemdDriver
  449. }
  450. // verifyPlatformContainerSettings performs platform-specific validation of the
  451. // hostconfig and config structures.
  452. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  453. var warnings []string
  454. sysInfo := sysinfo.New(true)
  455. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  456. if err != nil {
  457. return warnings, err
  458. }
  459. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  460. // no matter err is nil or not, w could have data in itself.
  461. warnings = append(warnings, w...)
  462. if err != nil {
  463. return warnings, err
  464. }
  465. if hostConfig.ShmSize < 0 {
  466. return warnings, fmt.Errorf("SHM size can not be less than 0")
  467. }
  468. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  469. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  470. }
  471. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  472. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  473. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  474. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  475. }
  476. // check for various conflicting options with user namespaces
  477. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  478. if hostConfig.Privileged {
  479. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  480. }
  481. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  482. return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
  483. }
  484. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  485. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  486. }
  487. }
  488. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  489. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  490. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  491. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  492. }
  493. }
  494. if hostConfig.Runtime == "" {
  495. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  496. }
  497. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  498. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  499. }
  500. for dest := range hostConfig.Tmpfs {
  501. if err := volume.ValidateTmpfsMountDestination(dest); err != nil {
  502. return warnings, err
  503. }
  504. }
  505. return warnings, nil
  506. }
  507. // platformReload updates configuration with platform specific options
  508. func (daemon *Daemon) platformReload(config *Config) map[string]string {
  509. if config.IsValueSet("runtimes") {
  510. daemon.configStore.Runtimes = config.Runtimes
  511. // Always set the default one
  512. daemon.configStore.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  513. }
  514. if config.DefaultRuntime != "" {
  515. daemon.configStore.DefaultRuntime = config.DefaultRuntime
  516. }
  517. if config.IsValueSet("default-shm-size") {
  518. daemon.configStore.ShmSize = config.ShmSize
  519. }
  520. // Update attributes
  521. var runtimeList bytes.Buffer
  522. for name, rt := range daemon.configStore.Runtimes {
  523. if runtimeList.Len() > 0 {
  524. runtimeList.WriteRune(' ')
  525. }
  526. runtimeList.WriteString(fmt.Sprintf("%s:%s", name, rt))
  527. }
  528. return map[string]string{
  529. "runtimes": runtimeList.String(),
  530. "default-runtime": daemon.configStore.DefaultRuntime,
  531. "default-shm-size": fmt.Sprintf("%d", daemon.configStore.ShmSize),
  532. }
  533. }
  534. // verifyDaemonSettings performs validation of daemon config struct
  535. func verifyDaemonSettings(config *Config) error {
  536. // Check for mutually incompatible config options
  537. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  538. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  539. }
  540. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  541. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  542. }
  543. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  544. config.bridgeConfig.EnableIPMasq = false
  545. }
  546. if err := VerifyCgroupDriver(config); err != nil {
  547. return err
  548. }
  549. if config.CgroupParent != "" && UsingSystemd(config) {
  550. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  551. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  552. }
  553. }
  554. if config.DefaultRuntime == "" {
  555. config.DefaultRuntime = stockRuntimeName
  556. }
  557. if config.Runtimes == nil {
  558. config.Runtimes = make(map[string]types.Runtime)
  559. }
  560. config.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  561. return nil
  562. }
  563. // checkSystem validates platform-specific requirements
  564. func checkSystem() error {
  565. if os.Geteuid() != 0 {
  566. return fmt.Errorf("The Docker daemon needs to be run as root")
  567. }
  568. return checkKernel()
  569. }
  570. // configureMaxThreads sets the Go runtime max threads threshold
  571. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  572. func configureMaxThreads(config *Config) error {
  573. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  574. if err != nil {
  575. return err
  576. }
  577. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  578. if err != nil {
  579. return err
  580. }
  581. maxThreads := (mtint / 100) * 90
  582. debug.SetMaxThreads(maxThreads)
  583. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  584. return nil
  585. }
  586. // configureKernelSecuritySupport configures and validates security support for the kernel
  587. func configureKernelSecuritySupport(config *Config, driverName string) error {
  588. if config.EnableSelinuxSupport {
  589. if !selinuxEnabled() {
  590. logrus.Warn("Docker could not enable SELinux on the host system")
  591. }
  592. } else {
  593. selinuxSetDisabled()
  594. }
  595. return nil
  596. }
  597. func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  598. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  599. if err != nil {
  600. return nil, err
  601. }
  602. controller, err := libnetwork.New(netOptions...)
  603. if err != nil {
  604. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  605. }
  606. if len(activeSandboxes) > 0 {
  607. logrus.Info("There are old running containers, the network config will not take affect")
  608. return controller, nil
  609. }
  610. // Initialize default network on "null"
  611. if n, _ := controller.NetworkByName("none"); n == nil {
  612. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  613. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  614. }
  615. }
  616. // Initialize default network on "host"
  617. if n, _ := controller.NetworkByName("host"); n == nil {
  618. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  619. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  620. }
  621. }
  622. // Clear stale bridge network
  623. if n, err := controller.NetworkByName("bridge"); err == nil {
  624. if err = n.Delete(); err != nil {
  625. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  626. }
  627. }
  628. if !config.DisableBridge {
  629. // Initialize default driver "bridge"
  630. if err := initBridgeDriver(controller, config); err != nil {
  631. return nil, err
  632. }
  633. } else {
  634. removeDefaultBridgeInterface()
  635. }
  636. return controller, nil
  637. }
  638. func driverOptions(config *Config) []nwconfig.Option {
  639. bridgeConfig := options.Generic{
  640. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  641. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  642. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy,
  643. "UserlandProxyPath": config.bridgeConfig.UserlandProxyPath}
  644. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  645. dOptions := []nwconfig.Option{}
  646. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  647. return dOptions
  648. }
  649. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  650. bridgeName := bridge.DefaultBridgeName
  651. if config.bridgeConfig.Iface != "" {
  652. bridgeName = config.bridgeConfig.Iface
  653. }
  654. netOption := map[string]string{
  655. bridge.BridgeName: bridgeName,
  656. bridge.DefaultBridge: strconv.FormatBool(true),
  657. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  658. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  659. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  660. }
  661. // --ip processing
  662. if config.bridgeConfig.DefaultIP != nil {
  663. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  664. }
  665. var (
  666. ipamV4Conf *libnetwork.IpamConf
  667. ipamV6Conf *libnetwork.IpamConf
  668. )
  669. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  670. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  671. if err != nil {
  672. return errors.Wrap(err, "list bridge addresses failed")
  673. }
  674. nw := nwList[0]
  675. if len(nwList) > 1 && config.bridgeConfig.FixedCIDR != "" {
  676. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  677. if err != nil {
  678. return errors.Wrap(err, "parse CIDR failed")
  679. }
  680. // Iterate through in case there are multiple addresses for the bridge
  681. for _, entry := range nwList {
  682. if fCIDR.Contains(entry.IP) {
  683. nw = entry
  684. break
  685. }
  686. }
  687. }
  688. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  689. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  690. if hip.IsGlobalUnicast() {
  691. ipamV4Conf.Gateway = nw.IP.String()
  692. }
  693. if config.bridgeConfig.IP != "" {
  694. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  695. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  696. if err != nil {
  697. return err
  698. }
  699. ipamV4Conf.Gateway = ip.String()
  700. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  701. 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)
  702. }
  703. if config.bridgeConfig.FixedCIDR != "" {
  704. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  705. if err != nil {
  706. return err
  707. }
  708. ipamV4Conf.SubPool = fCIDR.String()
  709. }
  710. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  711. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  712. }
  713. var deferIPv6Alloc bool
  714. if config.bridgeConfig.FixedCIDRv6 != "" {
  715. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  716. if err != nil {
  717. return err
  718. }
  719. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  720. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  721. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  722. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  723. // on this network until after the driver has created the endpoint and returned the
  724. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  725. ones, _ := fCIDRv6.Mask.Size()
  726. deferIPv6Alloc = ones <= 80
  727. if ipamV6Conf == nil {
  728. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  729. }
  730. ipamV6Conf.PreferredPool = fCIDRv6.String()
  731. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  732. // address belongs to the same network, we need to inform libnetwork about it, so
  733. // that it can be reserved with IPAM and it will not be given away to somebody else
  734. for _, nw6 := range nw6List {
  735. if fCIDRv6.Contains(nw6.IP) {
  736. ipamV6Conf.Gateway = nw6.IP.String()
  737. break
  738. }
  739. }
  740. }
  741. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  742. if ipamV6Conf == nil {
  743. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  744. }
  745. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  746. }
  747. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  748. v6Conf := []*libnetwork.IpamConf{}
  749. if ipamV6Conf != nil {
  750. v6Conf = append(v6Conf, ipamV6Conf)
  751. }
  752. // Initialize default network on "bridge" with the same name
  753. _, err = controller.NewNetwork("bridge", "bridge", "",
  754. libnetwork.NetworkOptionEnableIPv6(config.bridgeConfig.EnableIPv6),
  755. libnetwork.NetworkOptionDriverOpts(netOption),
  756. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  757. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  758. if err != nil {
  759. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  760. }
  761. return nil
  762. }
  763. // Remove default bridge interface if present (--bridge=none use case)
  764. func removeDefaultBridgeInterface() {
  765. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  766. if err := netlink.LinkDel(lnk); err != nil {
  767. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  768. }
  769. }
  770. }
  771. func (daemon *Daemon) getLayerInit() func(string) error {
  772. return daemon.setupInitLayer
  773. }
  774. // Parse the remapped root (user namespace) option, which can be one of:
  775. // username - valid username from /etc/passwd
  776. // username:groupname - valid username; valid groupname from /etc/group
  777. // uid - 32-bit unsigned int valid Linux UID value
  778. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  779. //
  780. // If no groupname is specified, and a username is specified, an attempt
  781. // will be made to lookup a gid for that username as a groupname
  782. //
  783. // If names are used, they are verified to exist in passwd/group
  784. func parseRemappedRoot(usergrp string) (string, string, error) {
  785. var (
  786. userID, groupID int
  787. username, groupname string
  788. )
  789. idparts := strings.Split(usergrp, ":")
  790. if len(idparts) > 2 {
  791. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  792. }
  793. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  794. // must be a uid; take it as valid
  795. userID = int(uid)
  796. luser, err := idtools.LookupUID(userID)
  797. if err != nil {
  798. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  799. }
  800. username = luser.Name
  801. if len(idparts) == 1 {
  802. // if the uid was numeric and no gid was specified, take the uid as the gid
  803. groupID = userID
  804. lgrp, err := idtools.LookupGID(groupID)
  805. if err != nil {
  806. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  807. }
  808. groupname = lgrp.Name
  809. }
  810. } else {
  811. lookupName := idparts[0]
  812. // special case: if the user specified "default", they want Docker to create or
  813. // use (after creation) the "dockremap" user/group for root remapping
  814. if lookupName == defaultIDSpecifier {
  815. lookupName = defaultRemappedID
  816. }
  817. luser, err := idtools.LookupUser(lookupName)
  818. if err != nil && idparts[0] != defaultIDSpecifier {
  819. // error if the name requested isn't the special "dockremap" ID
  820. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  821. } else if err != nil {
  822. // special case-- if the username == "default", then we have been asked
  823. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  824. // ranges will be used for the user and group mappings in user namespaced containers
  825. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  826. if err == nil {
  827. return defaultRemappedID, defaultRemappedID, nil
  828. }
  829. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  830. }
  831. username = luser.Name
  832. if len(idparts) == 1 {
  833. // we only have a string username, and no group specified; look up gid from username as group
  834. group, err := idtools.LookupGroup(lookupName)
  835. if err != nil {
  836. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  837. }
  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 := opts.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.machineMemory && daemon.machineMemory > 0 {
  1026. s.MemoryStats.Limit = daemon.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. defer f.Close()
  1066. stringScore := strconv.Itoa(score)
  1067. _, err = f.WriteString(stringScore)
  1068. if os.IsPermission(err) {
  1069. // Setting oom_score_adj does not work in an
  1070. // unprivileged container. Ignore the error, but log
  1071. // it if we appear not to be in that situation.
  1072. if !rsystem.RunningInUserNS() {
  1073. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1074. }
  1075. return nil
  1076. }
  1077. return err
  1078. }
  1079. func (daemon *Daemon) initCgroupsPath(path string) error {
  1080. if path == "/" || path == "." {
  1081. return nil
  1082. }
  1083. if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
  1084. return nil
  1085. }
  1086. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1087. // for the period and runtime as this limits what the children can be set to.
  1088. daemon.initCgroupsPath(filepath.Dir(path))
  1089. _, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
  1090. if err != nil {
  1091. return err
  1092. }
  1093. path = filepath.Join(root, path)
  1094. sysinfo := sysinfo.New(true)
  1095. if sysinfo.CPURealtimePeriod && daemon.configStore.CPURealtimePeriod != 0 {
  1096. if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
  1097. return err
  1098. }
  1099. if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_period_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimePeriod, 10)), 0700); err != nil {
  1100. return err
  1101. }
  1102. }
  1103. if sysinfo.CPURealtimeRuntime && daemon.configStore.CPURealtimeRuntime != 0 {
  1104. if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
  1105. return err
  1106. }
  1107. if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_runtime_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimeRuntime, 10)), 0700); err != nil {
  1108. return err
  1109. }
  1110. }
  1111. return nil
  1112. }
  1113. func (daemon *Daemon) setupSeccompProfile() error {
  1114. if daemon.configStore.SeccompProfile != "" {
  1115. daemon.seccompProfilePath = daemon.configStore.SeccompProfile
  1116. b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
  1117. if err != nil {
  1118. return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
  1119. }
  1120. daemon.seccompProfile = b
  1121. }
  1122. return nil
  1123. }