daemon_unix.go 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. //go:build linux || freebsd
  2. package daemon // import "github.com/docker/docker/daemon"
  3. import (
  4. "bufio"
  5. "context"
  6. "fmt"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "syscall"
  16. "time"
  17. "github.com/containerd/cgroups/v3"
  18. "github.com/containerd/containerd/pkg/userns"
  19. "github.com/containerd/log"
  20. "github.com/docker/docker/api/types/blkiodev"
  21. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  22. containertypes "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/api/types/network"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/config"
  26. "github.com/docker/docker/daemon/initlayer"
  27. "github.com/docker/docker/errdefs"
  28. "github.com/docker/docker/libcontainerd/remote"
  29. "github.com/docker/docker/libnetwork"
  30. nwconfig "github.com/docker/docker/libnetwork/config"
  31. "github.com/docker/docker/libnetwork/drivers/bridge"
  32. "github.com/docker/docker/libnetwork/netlabel"
  33. "github.com/docker/docker/libnetwork/options"
  34. lntypes "github.com/docker/docker/libnetwork/types"
  35. "github.com/docker/docker/opts"
  36. "github.com/docker/docker/pkg/idtools"
  37. "github.com/docker/docker/pkg/parsers"
  38. "github.com/docker/docker/pkg/parsers/kernel"
  39. "github.com/docker/docker/pkg/sysinfo"
  40. "github.com/docker/docker/runconfig"
  41. volumemounts "github.com/docker/docker/volume/mounts"
  42. "github.com/moby/sys/mount"
  43. specs "github.com/opencontainers/runtime-spec/specs-go"
  44. "github.com/opencontainers/selinux/go-selinux"
  45. "github.com/opencontainers/selinux/go-selinux/label"
  46. "github.com/pkg/errors"
  47. "github.com/vishvananda/netlink"
  48. "golang.org/x/sys/unix"
  49. )
  50. const (
  51. isWindows = false
  52. // These values were used to adjust the CPU-shares for older API versions,
  53. // but were not used for validation.
  54. //
  55. // TODO(thaJeztah): validate min/max values for CPU-shares, similar to Windows: https://github.com/moby/moby/issues/47340
  56. // https://github.com/moby/moby/blob/27e85c7b6885c2d21ae90791136d9aba78b83d01/daemon/daemon_windows.go#L97-L99
  57. //
  58. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  59. // linuxMinCPUShares = 2
  60. // linuxMaxCPUShares = 262144
  61. // It's not kernel limit, we want this 6M limit to account for overhead during startup, and to supply a reasonable functional container
  62. linuxMinMemory = 6291456
  63. // constants for remapped root settings
  64. defaultIDSpecifier = "default"
  65. defaultRemappedID = "dockremap"
  66. // constant for cgroup drivers
  67. cgroupFsDriver = "cgroupfs"
  68. cgroupSystemdDriver = "systemd"
  69. cgroupNoneDriver = "none"
  70. )
  71. type containerGetter interface {
  72. GetContainer(string) (*container.Container, error)
  73. }
  74. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  75. memory := specs.LinuxMemory{}
  76. if config.Memory > 0 {
  77. memory.Limit = &config.Memory
  78. }
  79. if config.MemoryReservation > 0 {
  80. memory.Reservation = &config.MemoryReservation
  81. }
  82. if config.MemorySwap > 0 {
  83. memory.Swap = &config.MemorySwap
  84. }
  85. if config.MemorySwappiness != nil {
  86. swappiness := uint64(*config.MemorySwappiness)
  87. memory.Swappiness = &swappiness
  88. }
  89. if config.OomKillDisable != nil {
  90. memory.DisableOOMKiller = config.OomKillDisable
  91. }
  92. if config.KernelMemory != 0 { //nolint:staticcheck // ignore SA1019: memory.Kernel is deprecated: kernel-memory limits are not supported in cgroups v2, and were obsoleted in [kernel v5.4]. This field should no longer be used, as it may be ignored by runtimes.
  93. memory.Kernel = &config.KernelMemory //nolint:staticcheck // ignore SA1019: memory.Kernel is deprecated: kernel-memory limits are not supported in cgroups v2, and were obsoleted in [kernel v5.4]. This field should no longer be used, as it may be ignored by runtimes.
  94. }
  95. if config.KernelMemoryTCP != 0 {
  96. memory.KernelTCP = &config.KernelMemoryTCP
  97. }
  98. if memory != (specs.LinuxMemory{}) {
  99. return &memory
  100. }
  101. return nil
  102. }
  103. func getPidsLimit(config containertypes.Resources) *specs.LinuxPids {
  104. if config.PidsLimit == nil {
  105. return nil
  106. }
  107. if *config.PidsLimit <= 0 {
  108. // docker API allows 0 and negative values to unset this to be consistent
  109. // with default values. When updating values, runc requires -1 to unset
  110. // the previous limit.
  111. return &specs.LinuxPids{Limit: -1}
  112. }
  113. return &specs.LinuxPids{Limit: *config.PidsLimit}
  114. }
  115. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  116. cpu := specs.LinuxCPU{}
  117. if config.CPUShares < 0 {
  118. return nil, fmt.Errorf("shares: invalid argument")
  119. }
  120. if config.CPUShares > 0 {
  121. shares := uint64(config.CPUShares)
  122. cpu.Shares = &shares
  123. }
  124. if config.CpusetCpus != "" {
  125. cpu.Cpus = config.CpusetCpus
  126. }
  127. if config.CpusetMems != "" {
  128. cpu.Mems = config.CpusetMems
  129. }
  130. if config.NanoCPUs > 0 {
  131. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  132. period := uint64(100 * time.Millisecond / time.Microsecond)
  133. quota := config.NanoCPUs * int64(period) / 1e9
  134. cpu.Period = &period
  135. cpu.Quota = &quota
  136. }
  137. if config.CPUPeriod != 0 {
  138. period := uint64(config.CPUPeriod)
  139. cpu.Period = &period
  140. }
  141. if config.CPUQuota != 0 {
  142. q := config.CPUQuota
  143. cpu.Quota = &q
  144. }
  145. if config.CPURealtimePeriod != 0 {
  146. period := uint64(config.CPURealtimePeriod)
  147. cpu.RealtimePeriod = &period
  148. }
  149. if config.CPURealtimeRuntime != 0 {
  150. c := config.CPURealtimeRuntime
  151. cpu.RealtimeRuntime = &c
  152. }
  153. if cpu != (specs.LinuxCPU{}) {
  154. return &cpu, nil
  155. }
  156. return nil, nil
  157. }
  158. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  159. var stat unix.Stat_t
  160. var blkioWeightDevices []specs.LinuxWeightDevice
  161. for _, weightDevice := range config.BlkioWeightDevice {
  162. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  163. return nil, errors.WithStack(&os.PathError{Op: "stat", Path: weightDevice.Path, Err: err})
  164. }
  165. weight := weightDevice.Weight
  166. d := specs.LinuxWeightDevice{Weight: &weight}
  167. // The type is 32bit on mips.
  168. d.Major = int64(unix.Major(uint64(stat.Rdev))) //nolint: unconvert
  169. d.Minor = int64(unix.Minor(uint64(stat.Rdev))) //nolint: unconvert
  170. blkioWeightDevices = append(blkioWeightDevices, d)
  171. }
  172. return blkioWeightDevices, nil
  173. }
  174. func (daemon *Daemon) parseSecurityOpt(cfg *config.Config, securityOptions *container.SecurityOptions, hostConfig *containertypes.HostConfig) error {
  175. securityOptions.NoNewPrivileges = cfg.NoNewPrivileges
  176. return parseSecurityOpt(securityOptions, hostConfig)
  177. }
  178. func parseSecurityOpt(securityOptions *container.SecurityOptions, config *containertypes.HostConfig) error {
  179. var (
  180. labelOpts []string
  181. err error
  182. )
  183. for _, opt := range config.SecurityOpt {
  184. if opt == "no-new-privileges" {
  185. securityOptions.NoNewPrivileges = true
  186. continue
  187. }
  188. if opt == "disable" {
  189. labelOpts = append(labelOpts, "disable")
  190. continue
  191. }
  192. var k, v string
  193. var ok bool
  194. if strings.Contains(opt, "=") {
  195. k, v, ok = strings.Cut(opt, "=")
  196. } else if strings.Contains(opt, ":") {
  197. k, v, ok = strings.Cut(opt, ":")
  198. log.G(context.TODO()).Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  199. }
  200. if !ok {
  201. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  202. }
  203. switch k {
  204. case "label":
  205. labelOpts = append(labelOpts, v)
  206. case "apparmor":
  207. securityOptions.AppArmorProfile = v
  208. case "seccomp":
  209. securityOptions.SeccompProfile = v
  210. case "no-new-privileges":
  211. noNewPrivileges, err := strconv.ParseBool(v)
  212. if err != nil {
  213. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  214. }
  215. securityOptions.NoNewPrivileges = noNewPrivileges
  216. default:
  217. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  218. }
  219. }
  220. securityOptions.ProcessLabel, securityOptions.MountLabel, err = label.InitLabels(labelOpts)
  221. return err
  222. }
  223. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.LinuxThrottleDevice, error) {
  224. var throttleDevices []specs.LinuxThrottleDevice
  225. var stat unix.Stat_t
  226. for _, d := range devs {
  227. if err := unix.Stat(d.Path, &stat); err != nil {
  228. return nil, errors.WithStack(&os.PathError{Op: "stat", Path: d.Path, Err: err})
  229. }
  230. d := specs.LinuxThrottleDevice{Rate: d.Rate}
  231. // the type is 32bit on mips
  232. d.Major = int64(unix.Major(uint64(stat.Rdev))) //nolint: unconvert
  233. d.Minor = int64(unix.Minor(uint64(stat.Rdev))) //nolint: unconvert
  234. throttleDevices = append(throttleDevices, d)
  235. }
  236. return throttleDevices, nil
  237. }
  238. // adjustParallelLimit takes a number of objects and a proposed limit and
  239. // figures out if it's reasonable (and adjusts it accordingly). This is only
  240. // used for daemon startup, which does a lot of parallel loading of containers
  241. // (and if we exceed RLIMIT_NOFILE then we're in trouble).
  242. func adjustParallelLimit(n int, limit int) int {
  243. // Rule-of-thumb overhead factor (how many files will each goroutine open
  244. // simultaneously). Yes, this is ugly but to be frank this whole thing is
  245. // ugly.
  246. const overhead = 2
  247. // On Linux, we need to ensure that parallelStartupJobs doesn't cause us to
  248. // exceed RLIMIT_NOFILE. If parallelStartupJobs is too large, we reduce it
  249. // and give a warning (since in theory the user should increase their
  250. // ulimits to the largest possible value for dockerd).
  251. var rlim unix.Rlimit
  252. if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlim); err != nil {
  253. log.G(context.TODO()).Warnf("Couldn't find dockerd's RLIMIT_NOFILE to double-check startup parallelism factor: %v", err)
  254. return limit
  255. }
  256. softRlimit := int(rlim.Cur)
  257. // Much fewer containers than RLIMIT_NOFILE. No need to adjust anything.
  258. if softRlimit > overhead*n {
  259. return limit
  260. }
  261. // RLIMIT_NOFILE big enough, no need to adjust anything.
  262. if softRlimit > overhead*limit {
  263. return limit
  264. }
  265. log.G(context.TODO()).Warnf("Found dockerd's open file ulimit (%v) is far too small -- consider increasing it significantly (at least %v)", softRlimit, overhead*limit)
  266. return softRlimit / overhead
  267. }
  268. // adaptContainerSettings is called during container creation to modify any
  269. // settings necessary in the HostConfig structure.
  270. func (daemon *Daemon) adaptContainerSettings(daemonCfg *config.Config, hostConfig *containertypes.HostConfig) error {
  271. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  272. // By default, MemorySwap is set to twice the size of Memory.
  273. hostConfig.MemorySwap = hostConfig.Memory * 2
  274. }
  275. if hostConfig.ShmSize == 0 {
  276. hostConfig.ShmSize = config.DefaultShmSize
  277. if daemonCfg != nil {
  278. hostConfig.ShmSize = int64(daemonCfg.ShmSize)
  279. }
  280. }
  281. // Set default IPC mode, if unset for container
  282. if hostConfig.IpcMode.IsEmpty() {
  283. m := config.DefaultIpcMode
  284. if daemonCfg != nil {
  285. m = containertypes.IpcMode(daemonCfg.IpcMode)
  286. }
  287. hostConfig.IpcMode = m
  288. }
  289. // Set default cgroup namespace mode, if unset for container
  290. if hostConfig.CgroupnsMode.IsEmpty() {
  291. // for cgroup v2: unshare cgroupns even for privileged containers
  292. // https://github.com/containers/libpod/pull/4374#issuecomment-549776387
  293. if hostConfig.Privileged && cgroups.Mode() != cgroups.Unified {
  294. hostConfig.CgroupnsMode = containertypes.CgroupnsModeHost
  295. } else {
  296. m := containertypes.CgroupnsModeHost
  297. if cgroups.Mode() == cgroups.Unified {
  298. m = containertypes.CgroupnsModePrivate
  299. }
  300. if daemonCfg != nil {
  301. m = containertypes.CgroupnsMode(daemonCfg.CgroupNamespaceMode)
  302. }
  303. hostConfig.CgroupnsMode = m
  304. }
  305. }
  306. adaptSharedNamespaceContainer(daemon, hostConfig)
  307. var err error
  308. secOpts, err := daemon.generateSecurityOpt(hostConfig)
  309. if err != nil {
  310. return err
  311. }
  312. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, secOpts...)
  313. if hostConfig.OomKillDisable == nil {
  314. defaultOomKillDisable := false
  315. hostConfig.OomKillDisable = &defaultOomKillDisable
  316. }
  317. return nil
  318. }
  319. // adaptSharedNamespaceContainer replaces container name with its ID in hostConfig.
  320. // To be more precisely, it modifies `container:name` to `container:ID` of PidMode, IpcMode
  321. // and NetworkMode.
  322. //
  323. // When a container shares its namespace with another container, use ID can keep the namespace
  324. // sharing connection between the two containers even the another container is renamed.
  325. func adaptSharedNamespaceContainer(daemon containerGetter, hostConfig *containertypes.HostConfig) {
  326. containerPrefix := "container:"
  327. if hostConfig.PidMode.IsContainer() {
  328. pidContainer := hostConfig.PidMode.Container()
  329. // if there is any error returned here, we just ignore it and leave it to be
  330. // handled in the following logic
  331. if c, err := daemon.GetContainer(pidContainer); err == nil {
  332. hostConfig.PidMode = containertypes.PidMode(containerPrefix + c.ID)
  333. }
  334. }
  335. if hostConfig.IpcMode.IsContainer() {
  336. ipcContainer := hostConfig.IpcMode.Container()
  337. if c, err := daemon.GetContainer(ipcContainer); err == nil {
  338. hostConfig.IpcMode = containertypes.IpcMode(containerPrefix + c.ID)
  339. }
  340. }
  341. if hostConfig.NetworkMode.IsContainer() {
  342. netContainer := hostConfig.NetworkMode.ConnectedContainer()
  343. if c, err := daemon.GetContainer(netContainer); err == nil {
  344. hostConfig.NetworkMode = containertypes.NetworkMode(containerPrefix + c.ID)
  345. }
  346. }
  347. }
  348. // verifyPlatformContainerResources performs platform-specific validation of the container's resource-configuration
  349. func verifyPlatformContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) (warnings []string, err error) {
  350. fixMemorySwappiness(resources)
  351. // memory subsystem checks and adjustments
  352. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  353. return warnings, fmt.Errorf("Minimum memory limit allowed is 6MB")
  354. }
  355. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  356. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  357. resources.Memory = 0
  358. resources.MemorySwap = -1
  359. }
  360. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  361. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  362. resources.MemorySwap = -1
  363. }
  364. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  365. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  366. }
  367. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  368. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  369. }
  370. if resources.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
  371. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  372. resources.MemorySwappiness = nil
  373. }
  374. if resources.MemorySwappiness != nil {
  375. swappiness := *resources.MemorySwappiness
  376. if swappiness < 0 || swappiness > 100 {
  377. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  378. }
  379. }
  380. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  381. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  382. resources.MemoryReservation = 0
  383. }
  384. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  385. return warnings, fmt.Errorf("Minimum memory reservation allowed is 6MB")
  386. }
  387. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  388. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  389. }
  390. if resources.KernelMemory > 0 {
  391. // Kernel memory limit is not supported on cgroup v2.
  392. // Even on cgroup v1, kernel memory limit (`kmem.limit_in_bytes`) has been deprecated since kernel 5.4.
  393. // https://github.com/torvalds/linux/commit/0158115f702b0ba208ab0b5adf44cae99b3ebcc7
  394. if !sysInfo.KernelMemory {
  395. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  396. resources.KernelMemory = 0
  397. }
  398. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  399. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 6MB")
  400. }
  401. if !kernel.CheckKernelVersion(4, 0, 0) {
  402. 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.")
  403. }
  404. }
  405. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  406. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  407. // warning the caller if they already wanted the feature to be off
  408. if *resources.OomKillDisable {
  409. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  410. }
  411. resources.OomKillDisable = nil
  412. }
  413. if resources.OomKillDisable != nil && *resources.OomKillDisable && resources.Memory == 0 {
  414. warnings = append(warnings, "OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.")
  415. }
  416. if resources.PidsLimit != nil && !sysInfo.PidsLimit {
  417. if *resources.PidsLimit > 0 {
  418. warnings = append(warnings, "Your kernel does not support PIDs limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  419. }
  420. resources.PidsLimit = nil
  421. }
  422. // cpu subsystem checks and adjustments
  423. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  424. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  425. }
  426. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  427. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  428. }
  429. if resources.NanoCPUs > 0 && !sysInfo.CPUCfs {
  430. return warnings, fmt.Errorf("NanoCPUs can not be set, as your kernel does not support CPU CFS scheduler or the cgroup is not mounted")
  431. }
  432. // The highest precision we could get on Linux is 0.001, by setting
  433. // cpu.cfs_period_us=1000ms
  434. // cpu.cfs_quota=1ms
  435. // See the following link for details:
  436. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  437. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  438. // The error message is 0.01 so that this is consistent with Windows
  439. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  440. 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())
  441. }
  442. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  443. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  444. resources.CPUShares = 0
  445. }
  446. if (resources.CPUPeriod != 0 || resources.CPUQuota != 0) && !sysInfo.CPUCfs {
  447. warnings = append(warnings, "Your kernel does not support CPU CFS scheduler. CPU period/quota discarded.")
  448. resources.CPUPeriod = 0
  449. resources.CPUQuota = 0
  450. }
  451. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  452. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  453. }
  454. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  455. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  456. }
  457. if resources.CPUPercent > 0 {
  458. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  459. resources.CPUPercent = 0
  460. }
  461. // cpuset subsystem checks and adjustments
  462. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  463. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  464. resources.CpusetCpus = ""
  465. resources.CpusetMems = ""
  466. }
  467. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  468. if err != nil {
  469. return warnings, errors.Wrapf(err, "Invalid value %s for cpuset cpus", resources.CpusetCpus)
  470. }
  471. if !cpusAvailable {
  472. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  473. }
  474. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  475. if err != nil {
  476. return warnings, errors.Wrapf(err, "Invalid value %s for cpuset mems", resources.CpusetMems)
  477. }
  478. if !memsAvailable {
  479. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  480. }
  481. // blkio subsystem checks and adjustments
  482. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  483. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  484. resources.BlkioWeight = 0
  485. }
  486. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  487. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  488. }
  489. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  490. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  491. }
  492. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  493. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  494. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  495. }
  496. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  497. 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.")
  498. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  499. }
  500. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  501. 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.")
  502. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  503. }
  504. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  505. 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.")
  506. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  507. }
  508. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  509. 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.")
  510. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  511. }
  512. return warnings, nil
  513. }
  514. func cgroupDriver(cfg *config.Config) string {
  515. if UsingSystemd(cfg) {
  516. return cgroupSystemdDriver
  517. }
  518. if cfg.Rootless {
  519. return cgroupNoneDriver
  520. }
  521. return cgroupFsDriver
  522. }
  523. // getCD gets the raw value of the native.cgroupdriver option, if set.
  524. func getCD(config *config.Config) string {
  525. for _, option := range config.ExecOptions {
  526. key, val, err := parsers.ParseKeyValueOpt(option)
  527. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  528. continue
  529. }
  530. return val
  531. }
  532. return ""
  533. }
  534. // verifyCgroupDriver validates native.cgroupdriver
  535. func verifyCgroupDriver(config *config.Config) error {
  536. cd := getCD(config)
  537. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  538. return nil
  539. }
  540. if cd == cgroupNoneDriver {
  541. return fmt.Errorf("native.cgroupdriver option %s is internally used and cannot be specified manually", cd)
  542. }
  543. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  544. }
  545. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  546. func UsingSystemd(config *config.Config) bool {
  547. cd := getCD(config)
  548. if cd == cgroupSystemdDriver {
  549. return true
  550. }
  551. // On cgroup v2 hosts, default to systemd driver
  552. if cd == "" && cgroups.Mode() == cgroups.Unified && isRunningSystemd() {
  553. return true
  554. }
  555. return false
  556. }
  557. var (
  558. runningSystemd bool
  559. detectSystemd sync.Once
  560. )
  561. // isRunningSystemd checks whether the host was booted with systemd as its init
  562. // system. This functions similarly to systemd's `sd_booted(3)`: internally, it
  563. // checks whether /run/systemd/system/ exists and is a directory.
  564. // http://www.freedesktop.org/software/systemd/man/sd_booted.html
  565. //
  566. // NOTE: This function comes from package github.com/coreos/go-systemd/util
  567. // It was borrowed here to avoid a dependency on cgo.
  568. func isRunningSystemd() bool {
  569. detectSystemd.Do(func() {
  570. fi, err := os.Lstat("/run/systemd/system")
  571. if err != nil {
  572. return
  573. }
  574. runningSystemd = fi.IsDir()
  575. })
  576. return runningSystemd
  577. }
  578. // verifyPlatformContainerSettings performs platform-specific validation of the
  579. // hostconfig and config structures.
  580. func verifyPlatformContainerSettings(daemon *Daemon, daemonCfg *configStore, hostConfig *containertypes.HostConfig, update bool) (warnings []string, err error) {
  581. if hostConfig == nil {
  582. return nil, nil
  583. }
  584. sysInfo := daemon.RawSysInfo()
  585. w, err := verifyPlatformContainerResources(&hostConfig.Resources, sysInfo, update)
  586. // no matter err is nil or not, w could have data in itself.
  587. warnings = append(warnings, w...)
  588. if err != nil {
  589. return warnings, err
  590. }
  591. if !hostConfig.IpcMode.Valid() {
  592. return warnings, errors.Errorf("invalid IPC mode: %v", hostConfig.IpcMode)
  593. }
  594. if !hostConfig.PidMode.Valid() {
  595. return warnings, errors.Errorf("invalid PID mode: %v", hostConfig.PidMode)
  596. }
  597. if hostConfig.ShmSize < 0 {
  598. return warnings, fmt.Errorf("SHM size can not be less than 0")
  599. }
  600. if !hostConfig.UTSMode.Valid() {
  601. return warnings, errors.Errorf("invalid UTS mode: %v", hostConfig.UTSMode)
  602. }
  603. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  604. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  605. }
  606. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  607. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  608. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  609. }
  610. if hostConfig.NetworkMode.IsHost() && len(hostConfig.PortBindings) > 0 {
  611. warnings = append(warnings, "Published ports are discarded when using host network mode")
  612. }
  613. // check for various conflicting options with user namespaces
  614. if daemonCfg.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  615. if hostConfig.Privileged {
  616. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  617. }
  618. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  619. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  620. }
  621. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  622. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  623. }
  624. }
  625. if hostConfig.CgroupParent != "" && UsingSystemd(&daemonCfg.Config) {
  626. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  627. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  628. return warnings, fmt.Errorf(`cgroup-parent for systemd cgroup should be a valid slice named as "xxx.slice"`)
  629. }
  630. }
  631. if hostConfig.Runtime == "" {
  632. hostConfig.Runtime = daemonCfg.Runtimes.Default
  633. }
  634. if _, _, err := daemonCfg.Runtimes.Get(hostConfig.Runtime); err != nil {
  635. return warnings, err
  636. }
  637. parser := volumemounts.NewParser()
  638. for dest := range hostConfig.Tmpfs {
  639. if err := parser.ValidateTmpfsMountDestination(dest); err != nil {
  640. return warnings, err
  641. }
  642. }
  643. if !hostConfig.CgroupnsMode.Valid() {
  644. return warnings, fmt.Errorf("invalid cgroup namespace mode: %v", hostConfig.CgroupnsMode)
  645. }
  646. if hostConfig.CgroupnsMode.IsPrivate() {
  647. if !sysInfo.CgroupNamespaces {
  648. warnings = append(warnings, "Your kernel does not support cgroup namespaces. Cgroup namespace setting discarded.")
  649. }
  650. }
  651. return warnings, nil
  652. }
  653. // verifyDaemonSettings performs validation of daemon config struct
  654. func verifyDaemonSettings(conf *config.Config) error {
  655. if conf.ContainerdNamespace == conf.ContainerdPluginNamespace {
  656. return errors.New("containers namespace and plugins namespace cannot be the same")
  657. }
  658. // Check for mutually incompatible config options
  659. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  660. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  661. }
  662. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  663. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  664. }
  665. if conf.BridgeConfig.EnableIP6Tables && !conf.Experimental {
  666. return fmt.Errorf("ip6tables rules are only available if experimental features are enabled")
  667. }
  668. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  669. conf.BridgeConfig.EnableIPMasq = false
  670. }
  671. if err := verifyCgroupDriver(conf); err != nil {
  672. return err
  673. }
  674. if conf.CgroupParent != "" && UsingSystemd(conf) {
  675. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  676. return fmt.Errorf(`cgroup-parent for systemd cgroup should be a valid slice named as "xxx.slice"`)
  677. }
  678. }
  679. if conf.Rootless && UsingSystemd(conf) && cgroups.Mode() != cgroups.Unified {
  680. return fmt.Errorf("exec-opt native.cgroupdriver=systemd requires cgroup v2 for rootless mode")
  681. }
  682. return nil
  683. }
  684. // checkSystem validates platform-specific requirements
  685. func checkSystem() error {
  686. return nil
  687. }
  688. // configureMaxThreads sets the Go runtime max threads threshold
  689. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  690. func configureMaxThreads(config *config.Config) error {
  691. mt, err := os.ReadFile("/proc/sys/kernel/threads-max")
  692. if err != nil {
  693. return err
  694. }
  695. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  696. if err != nil {
  697. return err
  698. }
  699. maxThreads := (mtint / 100) * 90
  700. debug.SetMaxThreads(maxThreads)
  701. log.G(context.TODO()).Debugf("Golang's threads limit set to %d", maxThreads)
  702. return nil
  703. }
  704. func overlaySupportsSelinux() (bool, error) {
  705. f, err := os.Open("/proc/kallsyms")
  706. if err != nil {
  707. if os.IsNotExist(err) {
  708. return false, nil
  709. }
  710. return false, err
  711. }
  712. defer f.Close()
  713. s := bufio.NewScanner(f)
  714. for s.Scan() {
  715. if strings.HasSuffix(s.Text(), " security_inode_copy_up") {
  716. return true, nil
  717. }
  718. }
  719. return false, s.Err()
  720. }
  721. // configureKernelSecuritySupport configures and validates security support for the kernel
  722. func configureKernelSecuritySupport(config *config.Config, driverName string) error {
  723. if config.EnableSelinuxSupport {
  724. if !selinux.GetEnabled() {
  725. log.G(context.TODO()).Warn("Docker could not enable SELinux on the host system")
  726. return nil
  727. }
  728. if driverName == "overlay2" || driverName == "overlayfs" {
  729. // If driver is overlay2, make sure kernel
  730. // supports selinux with overlay.
  731. supported, err := overlaySupportsSelinux()
  732. if err != nil {
  733. return err
  734. }
  735. if !supported {
  736. log.G(context.TODO()).Warnf("SELinux is not supported with the %v graph driver on this kernel", driverName)
  737. }
  738. }
  739. } else {
  740. selinux.SetDisabled()
  741. }
  742. return nil
  743. }
  744. // initNetworkController initializes the libnetwork controller and configures
  745. // network settings. If there's active sandboxes, configuration changes will not
  746. // take effect.
  747. func (daemon *Daemon) initNetworkController(cfg *config.Config, activeSandboxes map[string]interface{}) error {
  748. netOptions, err := daemon.networkOptions(cfg, daemon.PluginStore, activeSandboxes)
  749. if err != nil {
  750. return err
  751. }
  752. daemon.netController, err = libnetwork.New(netOptions...)
  753. if err != nil {
  754. return fmt.Errorf("error obtaining controller instance: %v", err)
  755. }
  756. if len(activeSandboxes) > 0 {
  757. log.G(context.TODO()).Info("there are running containers, updated network configuration will not take affect")
  758. } else if err := configureNetworking(daemon.netController, cfg); err != nil {
  759. return err
  760. }
  761. // Set HostGatewayIP to the default bridge's IP if it is empty
  762. setHostGatewayIP(daemon.netController, cfg)
  763. return nil
  764. }
  765. func configureNetworking(controller *libnetwork.Controller, conf *config.Config) error {
  766. // Create predefined network "none"
  767. if n, _ := controller.NetworkByName(network.NetworkNone); n == nil {
  768. if _, err := controller.NewNetwork("null", network.NetworkNone, "", libnetwork.NetworkOptionPersist(true)); err != nil {
  769. return errors.Wrapf(err, `error creating default %q network`, network.NetworkNone)
  770. }
  771. }
  772. // Create predefined network "host"
  773. if n, _ := controller.NetworkByName(network.NetworkHost); n == nil {
  774. if _, err := controller.NewNetwork("host", network.NetworkHost, "", libnetwork.NetworkOptionPersist(true)); err != nil {
  775. return errors.Wrapf(err, `error creating default %q network`, network.NetworkHost)
  776. }
  777. }
  778. // Clear stale bridge network
  779. if n, err := controller.NetworkByName(network.NetworkBridge); err == nil {
  780. if err = n.Delete(); err != nil {
  781. return errors.Wrapf(err, `could not delete the default %q network`, network.NetworkBridge)
  782. }
  783. if len(conf.NetworkConfig.DefaultAddressPools.Value()) > 0 && !conf.LiveRestoreEnabled {
  784. removeDefaultBridgeInterface()
  785. }
  786. }
  787. if !conf.DisableBridge {
  788. // Initialize default driver "bridge"
  789. if err := initBridgeDriver(controller, conf.BridgeConfig); err != nil {
  790. return err
  791. }
  792. } else {
  793. removeDefaultBridgeInterface()
  794. }
  795. return nil
  796. }
  797. // setHostGatewayIP sets cfg.HostGatewayIP to the default bridge's IP if it is empty.
  798. func setHostGatewayIP(controller *libnetwork.Controller, config *config.Config) {
  799. if config.HostGatewayIP != nil {
  800. return
  801. }
  802. if n, err := controller.NetworkByName(network.NetworkBridge); err == nil {
  803. v4Info, v6Info := n.IpamInfo()
  804. if len(v4Info) > 0 {
  805. config.HostGatewayIP = v4Info[0].Gateway.IP
  806. } else if len(v6Info) > 0 {
  807. config.HostGatewayIP = v6Info[0].Gateway.IP
  808. }
  809. }
  810. }
  811. func driverOptions(config *config.Config) nwconfig.Option {
  812. return nwconfig.OptionDriverConfig("bridge", options.Generic{
  813. netlabel.GenericData: options.Generic{
  814. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  815. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  816. "EnableIP6Tables": config.BridgeConfig.EnableIP6Tables,
  817. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  818. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath,
  819. },
  820. })
  821. }
  822. func initBridgeDriver(controller *libnetwork.Controller, cfg config.BridgeConfig) error {
  823. bridgeName := bridge.DefaultBridgeName
  824. if cfg.Iface != "" {
  825. bridgeName = cfg.Iface
  826. }
  827. netOption := map[string]string{
  828. bridge.BridgeName: bridgeName,
  829. bridge.DefaultBridge: strconv.FormatBool(true),
  830. netlabel.DriverMTU: strconv.Itoa(cfg.MTU),
  831. bridge.EnableIPMasquerade: strconv.FormatBool(cfg.EnableIPMasq),
  832. bridge.EnableICC: strconv.FormatBool(cfg.InterContainerCommunication),
  833. }
  834. // --ip processing
  835. if cfg.DefaultIP != nil {
  836. netOption[bridge.DefaultBindingIP] = cfg.DefaultIP.String()
  837. }
  838. ipamV4Conf := &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  839. // By default, libnetwork will request an arbitrary available address
  840. // pool for the network from the configured IPAM allocator.
  841. // Configure it to use the IPv4 network ranges of the existing bridge
  842. // interface if one exists with IPv4 addresses assigned to it.
  843. nwList, nw6List, err := ifaceAddrs(bridgeName)
  844. if err != nil {
  845. return errors.Wrap(err, "list bridge addresses failed")
  846. }
  847. if len(nwList) > 0 {
  848. nw := nwList[0]
  849. if len(nwList) > 1 && cfg.FixedCIDR != "" {
  850. _, fCIDR, err := net.ParseCIDR(cfg.FixedCIDR)
  851. if err != nil {
  852. return errors.Wrap(err, "parse CIDR failed")
  853. }
  854. // Iterate through in case there are multiple addresses for the bridge
  855. for _, entry := range nwList {
  856. if fCIDR.Contains(entry.IP) {
  857. nw = entry
  858. break
  859. }
  860. }
  861. }
  862. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  863. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  864. if hip.IsGlobalUnicast() {
  865. ipamV4Conf.Gateway = nw.IP.String()
  866. }
  867. }
  868. if cfg.IP != "" {
  869. ip, ipNet, err := net.ParseCIDR(cfg.IP)
  870. if err != nil {
  871. return err
  872. }
  873. ipamV4Conf.PreferredPool = ipNet.String()
  874. ipamV4Conf.Gateway = ip.String()
  875. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  876. log.G(context.TODO()).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)
  877. }
  878. if cfg.FixedCIDR != "" {
  879. _, fCIDR, err := net.ParseCIDR(cfg.FixedCIDR)
  880. if err != nil {
  881. return err
  882. }
  883. ipamV4Conf.SubPool = fCIDR.String()
  884. if ipamV4Conf.PreferredPool == "" {
  885. ipamV4Conf.PreferredPool = fCIDR.String()
  886. }
  887. }
  888. if cfg.DefaultGatewayIPv4 != nil {
  889. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = cfg.DefaultGatewayIPv4.String()
  890. }
  891. var (
  892. deferIPv6Alloc bool
  893. ipamV6Conf *libnetwork.IpamConf
  894. )
  895. if cfg.EnableIPv6 && cfg.FixedCIDRv6 == "" {
  896. return errdefs.InvalidParameter(errors.New("IPv6 is enabled for the default bridge, but no subnet is configured. Specify an IPv6 subnet using --fixed-cidr-v6"))
  897. } else if cfg.FixedCIDRv6 != "" {
  898. _, fCIDRv6, err := net.ParseCIDR(cfg.FixedCIDRv6)
  899. if err != nil {
  900. return err
  901. }
  902. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  903. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  904. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  905. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  906. // on this network until after the driver has created the endpoint and returned the
  907. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  908. ones, _ := fCIDRv6.Mask.Size()
  909. deferIPv6Alloc = ones <= 80
  910. ipamV6Conf = &libnetwork.IpamConf{
  911. AuxAddresses: make(map[string]string),
  912. PreferredPool: fCIDRv6.String(),
  913. }
  914. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  915. // address belongs to the same network, we need to inform libnetwork about it, so
  916. // that it can be reserved with IPAM and it will not be given away to somebody else
  917. for _, nw6 := range nw6List {
  918. if fCIDRv6.Contains(nw6.IP) {
  919. ipamV6Conf.Gateway = nw6.IP.String()
  920. break
  921. }
  922. }
  923. }
  924. if cfg.DefaultGatewayIPv6 != nil {
  925. if ipamV6Conf == nil {
  926. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  927. }
  928. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = cfg.DefaultGatewayIPv6.String()
  929. }
  930. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  931. v6Conf := []*libnetwork.IpamConf{}
  932. if ipamV6Conf != nil {
  933. v6Conf = append(v6Conf, ipamV6Conf)
  934. }
  935. // Initialize default network on "bridge" with the same name
  936. _, err = controller.NewNetwork("bridge", network.NetworkBridge, "",
  937. libnetwork.NetworkOptionEnableIPv6(cfg.EnableIPv6),
  938. libnetwork.NetworkOptionDriverOpts(netOption),
  939. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  940. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  941. if err != nil {
  942. return fmt.Errorf(`error creating default %q network: %v`, network.NetworkBridge, err)
  943. }
  944. return nil
  945. }
  946. // Remove default bridge interface if present (--bridge=none use case)
  947. func removeDefaultBridgeInterface() {
  948. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  949. if err := netlink.LinkDel(lnk); err != nil {
  950. log.G(context.TODO()).Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  951. }
  952. }
  953. }
  954. func setupInitLayer(idMapping idtools.IdentityMapping) func(string) error {
  955. return func(initPath string) error {
  956. return initlayer.Setup(initPath, idMapping.RootPair())
  957. }
  958. }
  959. // Parse the remapped root (user namespace) option, which can be one of:
  960. //
  961. // - username - valid username from /etc/passwd
  962. // - username:groupname - valid username; valid groupname from /etc/group
  963. // - uid - 32-bit unsigned int valid Linux UID value
  964. // - uid:gid - uid value; 32-bit unsigned int Linux GID value
  965. //
  966. // If no groupname is specified, and a username is specified, an attempt
  967. // will be made to lookup a gid for that username as a groupname
  968. //
  969. // If names are used, they are verified to exist in passwd/group
  970. func parseRemappedRoot(usergrp string) (string, string, error) {
  971. var (
  972. userID, groupID int
  973. username, groupname string
  974. )
  975. idparts := strings.Split(usergrp, ":")
  976. if len(idparts) > 2 {
  977. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  978. }
  979. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  980. // must be a uid; take it as valid
  981. userID = int(uid)
  982. luser, err := idtools.LookupUID(userID)
  983. if err != nil {
  984. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  985. }
  986. username = luser.Name
  987. if len(idparts) == 1 {
  988. // if the uid was numeric and no gid was specified, take the uid as the gid
  989. groupID = userID
  990. lgrp, err := idtools.LookupGID(groupID)
  991. if err != nil {
  992. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  993. }
  994. groupname = lgrp.Name
  995. }
  996. } else {
  997. lookupName := idparts[0]
  998. // special case: if the user specified "default", they want Docker to create or
  999. // use (after creation) the "dockremap" user/group for root remapping
  1000. if lookupName == defaultIDSpecifier {
  1001. lookupName = defaultRemappedID
  1002. }
  1003. luser, err := idtools.LookupUser(lookupName)
  1004. if err != nil && idparts[0] != defaultIDSpecifier {
  1005. // error if the name requested isn't the special "dockremap" ID
  1006. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  1007. } else if err != nil {
  1008. // special case-- if the username == "default", then we have been asked
  1009. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  1010. // ranges will be used for the user and group mappings in user namespaced containers
  1011. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  1012. if err == nil {
  1013. return defaultRemappedID, defaultRemappedID, nil
  1014. }
  1015. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  1016. }
  1017. username = luser.Name
  1018. if len(idparts) == 1 {
  1019. // we only have a string username, and no group specified; look up gid from username as group
  1020. group, err := idtools.LookupGroup(lookupName)
  1021. if err != nil {
  1022. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  1023. }
  1024. groupname = group.Name
  1025. }
  1026. }
  1027. if len(idparts) == 2 {
  1028. // groupname or gid is separately specified and must be resolved
  1029. // to an unsigned 32-bit gid
  1030. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  1031. // must be a gid, take it as valid
  1032. groupID = int(gid)
  1033. lgrp, err := idtools.LookupGID(groupID)
  1034. if err != nil {
  1035. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  1036. }
  1037. groupname = lgrp.Name
  1038. } else {
  1039. // not a number; attempt a lookup
  1040. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  1041. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  1042. }
  1043. groupname = idparts[1]
  1044. }
  1045. }
  1046. return username, groupname, nil
  1047. }
  1048. func setupRemappedRoot(config *config.Config) (idtools.IdentityMapping, error) {
  1049. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  1050. return idtools.IdentityMapping{}, fmt.Errorf("User namespaces are only supported on Linux")
  1051. }
  1052. // if the daemon was started with remapped root option, parse
  1053. // the config option to the int uid,gid values
  1054. if config.RemappedRoot != "" {
  1055. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  1056. if err != nil {
  1057. return idtools.IdentityMapping{}, err
  1058. }
  1059. if username == "root" {
  1060. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  1061. // effectively
  1062. log.G(context.TODO()).Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  1063. return idtools.IdentityMapping{}, nil
  1064. }
  1065. log.G(context.TODO()).Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s", username)
  1066. // update remapped root setting now that we have resolved them to actual names
  1067. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  1068. mappings, err := idtools.LoadIdentityMapping(username)
  1069. if err != nil {
  1070. return idtools.IdentityMapping{}, errors.Wrap(err, "Can't create ID mappings")
  1071. }
  1072. return mappings, nil
  1073. }
  1074. return idtools.IdentityMapping{}, nil
  1075. }
  1076. func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools.Identity) error {
  1077. config.Root = rootDir
  1078. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  1079. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  1080. // (e.g. mounted layers of a container) can traverse this path.
  1081. // The user namespace support will create subdirectories for the remapped root host uid:gid
  1082. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  1083. // layer content subtrees.
  1084. if _, err := os.Stat(rootDir); err == nil {
  1085. // root current exists; verify the access bits are correct by setting them
  1086. if err = os.Chmod(rootDir, 0o711); err != nil {
  1087. return err
  1088. }
  1089. } else if os.IsNotExist(err) {
  1090. // no root exists yet, create it 0711 with root:root ownership
  1091. if err := os.MkdirAll(rootDir, 0o711); err != nil {
  1092. return err
  1093. }
  1094. }
  1095. id := idtools.Identity{UID: idtools.CurrentIdentity().UID, GID: remappedRoot.GID}
  1096. // First make sure the current root dir has the correct perms.
  1097. if err := idtools.MkdirAllAndChown(config.Root, 0o710, id); err != nil {
  1098. return errors.Wrapf(err, "could not create or set daemon root permissions: %s", config.Root)
  1099. }
  1100. // if user namespaces are enabled we will create a subtree underneath the specified root
  1101. // with any/all specified remapped root uid/gid options on the daemon creating
  1102. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  1103. // `chdir()` to work for containers namespaced to that uid/gid)
  1104. if config.RemappedRoot != "" {
  1105. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", remappedRoot.UID, remappedRoot.GID))
  1106. log.G(context.TODO()).Debugf("Creating user namespaced daemon root: %s", config.Root)
  1107. // Create the root directory if it doesn't exist
  1108. if err := idtools.MkdirAllAndChown(config.Root, 0o710, id); err != nil {
  1109. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  1110. }
  1111. // we also need to verify that any pre-existing directories in the path to
  1112. // the graphroot won't block access to remapped root--if any pre-existing directory
  1113. // has strict permissions that don't allow "x", container start will fail, so
  1114. // better to warn and fail now
  1115. dirPath := config.Root
  1116. for {
  1117. dirPath = filepath.Dir(dirPath)
  1118. if dirPath == "/" {
  1119. break
  1120. }
  1121. if !canAccess(dirPath, remappedRoot) {
  1122. 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)
  1123. }
  1124. }
  1125. }
  1126. if err := setupDaemonRootPropagation(config); err != nil {
  1127. log.G(context.TODO()).WithError(err).WithField("dir", config.Root).Warn("Error while setting daemon root propagation, this is not generally critical but may cause some functionality to not work or fallback to less desirable behavior")
  1128. }
  1129. return nil
  1130. }
  1131. // canAccess takes a valid (existing) directory and a uid, gid pair and determines
  1132. // if that uid, gid pair has access (execute bit) to the directory.
  1133. //
  1134. // Note: this is a very rudimentary check, and may not produce accurate results,
  1135. // so should not be used for anything other than the current use, see:
  1136. // https://github.com/moby/moby/issues/43724
  1137. func canAccess(path string, pair idtools.Identity) bool {
  1138. statInfo, err := os.Stat(path)
  1139. if err != nil {
  1140. return false
  1141. }
  1142. perms := statInfo.Mode().Perm()
  1143. if perms&0o001 == 0o001 {
  1144. // world access
  1145. return true
  1146. }
  1147. ssi := statInfo.Sys().(*syscall.Stat_t)
  1148. if ssi.Uid == uint32(pair.UID) && (perms&0o100 == 0o100) {
  1149. // owner access.
  1150. return true
  1151. }
  1152. if ssi.Gid == uint32(pair.GID) && (perms&0o010 == 0o010) {
  1153. // group access.
  1154. return true
  1155. }
  1156. return false
  1157. }
  1158. func setupDaemonRootPropagation(cfg *config.Config) error {
  1159. rootParentMount, mountOptions, err := getSourceMount(cfg.Root)
  1160. if err != nil {
  1161. return errors.Wrap(err, "error getting daemon root's parent mount")
  1162. }
  1163. var cleanupOldFile bool
  1164. cleanupFile := getUnmountOnShutdownPath(cfg)
  1165. defer func() {
  1166. if !cleanupOldFile {
  1167. return
  1168. }
  1169. if err := os.Remove(cleanupFile); err != nil && !os.IsNotExist(err) {
  1170. log.G(context.TODO()).WithError(err).WithField("file", cleanupFile).Warn("could not clean up old root propagation unmount file")
  1171. }
  1172. }()
  1173. if hasMountInfoOption(mountOptions, sharedPropagationOption, slavePropagationOption) {
  1174. cleanupOldFile = true
  1175. return nil
  1176. }
  1177. if err := mount.MakeShared(cfg.Root); err != nil {
  1178. return errors.Wrap(err, "could not setup daemon root propagation to shared")
  1179. }
  1180. // check the case where this may have already been a mount to itself.
  1181. // If so then the daemon only performed a remount and should not try to unmount this later.
  1182. if rootParentMount == cfg.Root {
  1183. cleanupOldFile = true
  1184. return nil
  1185. }
  1186. if err := os.MkdirAll(filepath.Dir(cleanupFile), 0o700); err != nil {
  1187. return errors.Wrap(err, "error creating dir to store mount cleanup file")
  1188. }
  1189. if err := os.WriteFile(cleanupFile, nil, 0o600); err != nil {
  1190. return errors.Wrap(err, "error writing file to signal mount cleanup on shutdown")
  1191. }
  1192. return nil
  1193. }
  1194. // getUnmountOnShutdownPath generates the path to used when writing the file that signals to the daemon that on shutdown
  1195. // the daemon root should be unmounted.
  1196. func getUnmountOnShutdownPath(config *config.Config) string {
  1197. return filepath.Join(config.ExecRoot, "unmount-on-shutdown")
  1198. }
  1199. // registerLinks registers network links between container and other containers
  1200. // with the daemon using the specification in hostConfig.
  1201. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1202. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1203. return nil
  1204. }
  1205. for _, l := range hostConfig.Links {
  1206. name, alias, err := opts.ParseLink(l)
  1207. if err != nil {
  1208. return err
  1209. }
  1210. child, err := daemon.GetContainer(name)
  1211. if err != nil {
  1212. if errdefs.IsNotFound(err) {
  1213. // Trying to link to a non-existing container is not valid, and
  1214. // should return an "invalid parameter" error. Returning a "not
  1215. // found" error here would make the client report the container's
  1216. // image could not be found (see moby/moby#39823)
  1217. err = errdefs.InvalidParameter(err)
  1218. }
  1219. return errors.Wrapf(err, "could not get container for %s", name)
  1220. }
  1221. for child.HostConfig.NetworkMode.IsContainer() {
  1222. cid := child.HostConfig.NetworkMode.ConnectedContainer()
  1223. child, err = daemon.GetContainer(cid)
  1224. if err != nil {
  1225. if errdefs.IsNotFound(err) {
  1226. // Trying to link to a non-existing container is not valid, and
  1227. // should return an "invalid parameter" error. Returning a "not
  1228. // found" error here would make the client report the container's
  1229. // image could not be found (see moby/moby#39823)
  1230. err = errdefs.InvalidParameter(err)
  1231. }
  1232. return errors.Wrapf(err, "could not get container for %s", cid)
  1233. }
  1234. }
  1235. if child.HostConfig.NetworkMode.IsHost() {
  1236. return runconfig.ErrConflictHostNetworkAndLinks
  1237. }
  1238. if err := daemon.registerLink(container, child, alias); err != nil {
  1239. return err
  1240. }
  1241. }
  1242. return nil
  1243. }
  1244. // conditionalMountOnStart is a platform specific helper function during the
  1245. // container start to call mount.
  1246. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1247. return daemon.Mount(container)
  1248. }
  1249. // conditionalUnmountOnCleanup is a platform specific helper function called
  1250. // during the cleanup of a container to unmount.
  1251. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1252. return daemon.Unmount(container)
  1253. }
  1254. // setDefaultIsolation determines the default isolation mode for the
  1255. // daemon to run in. This is only applicable on Windows
  1256. func (daemon *Daemon) setDefaultIsolation(*config.Config) error {
  1257. return nil
  1258. }
  1259. // This is used to allow removal of mountpoints that may be mounted in other
  1260. // namespaces on RHEL based kernels starting from RHEL 7.4.
  1261. // Without this setting, removals on these RHEL based kernels may fail with
  1262. // "device or resource busy".
  1263. // This setting is not available in upstream kernels as it is not configurable,
  1264. // but has been in the upstream kernels since 3.15.
  1265. func setMayDetachMounts() error {
  1266. f, err := os.OpenFile("/proc/sys/fs/may_detach_mounts", os.O_WRONLY, 0)
  1267. if err != nil {
  1268. if os.IsNotExist(err) {
  1269. return nil
  1270. }
  1271. return errors.Wrap(err, "error opening may_detach_mounts kernel config file")
  1272. }
  1273. defer f.Close()
  1274. _, err = f.WriteString("1")
  1275. if os.IsPermission(err) {
  1276. // Setting may_detach_mounts does not work in an
  1277. // unprivileged container. Ignore the error, but log
  1278. // it if we appear not to be in that situation.
  1279. if !userns.RunningInUserNS() {
  1280. log.G(context.TODO()).Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
  1281. }
  1282. return nil
  1283. }
  1284. return err
  1285. }
  1286. func (daemon *Daemon) initCPURtController(cfg *config.Config, mnt, path string) error {
  1287. if path == "/" || path == "." {
  1288. return nil
  1289. }
  1290. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1291. // for the period and runtime as this limits what the children can be set to.
  1292. if err := daemon.initCPURtController(cfg, mnt, filepath.Dir(path)); err != nil {
  1293. return err
  1294. }
  1295. path = filepath.Join(mnt, path)
  1296. if err := os.MkdirAll(path, 0o755); err != nil {
  1297. return err
  1298. }
  1299. if err := maybeCreateCPURealTimeFile(cfg.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1300. return err
  1301. }
  1302. return maybeCreateCPURealTimeFile(cfg.CPURealtimeRuntime, "cpu.rt_runtime_us", path)
  1303. }
  1304. func maybeCreateCPURealTimeFile(configValue int64, file string, path string) error {
  1305. if configValue == 0 {
  1306. return nil
  1307. }
  1308. return os.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0o700)
  1309. }
  1310. func (daemon *Daemon) setupSeccompProfile(cfg *config.Config) error {
  1311. switch profile := cfg.SeccompProfile; profile {
  1312. case "", config.SeccompProfileDefault:
  1313. daemon.seccompProfilePath = config.SeccompProfileDefault
  1314. case config.SeccompProfileUnconfined:
  1315. daemon.seccompProfilePath = config.SeccompProfileUnconfined
  1316. default:
  1317. daemon.seccompProfilePath = profile
  1318. b, err := os.ReadFile(profile)
  1319. if err != nil {
  1320. return fmt.Errorf("opening seccomp profile (%s) failed: %v", profile, err)
  1321. }
  1322. daemon.seccompProfile = b
  1323. }
  1324. return nil
  1325. }
  1326. func getSysInfo(cfg *config.Config) *sysinfo.SysInfo {
  1327. var siOpts []sysinfo.Opt
  1328. if cgroupDriver(cfg) == cgroupSystemdDriver {
  1329. if euid := os.Getenv("ROOTLESSKIT_PARENT_EUID"); euid != "" {
  1330. siOpts = append(siOpts, sysinfo.WithCgroup2GroupPath("/user.slice/user-"+euid+".slice"))
  1331. }
  1332. }
  1333. return sysinfo.New(siOpts...)
  1334. }
  1335. func (daemon *Daemon) initLibcontainerd(ctx context.Context, cfg *config.Config) error {
  1336. var err error
  1337. daemon.containerd, err = remote.NewClient(
  1338. ctx,
  1339. daemon.containerdClient,
  1340. filepath.Join(cfg.ExecRoot, "containerd"),
  1341. cfg.ContainerdNamespace,
  1342. daemon,
  1343. )
  1344. return err
  1345. }
  1346. func recursiveUnmount(target string) error {
  1347. return mount.RecursiveUnmount(target)
  1348. }