daemon_unix.go 48 KB

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