daemon_unix.go 48 KB

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