daemon_unix.go 54 KB

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