daemon_unix.go 48 KB

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