daemon_unix.go 48 KB

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