daemon_unix.go 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. //go:build linux || freebsd
  2. // +build linux freebsd
  3. package daemon // import "github.com/docker/docker/daemon"
  4. import (
  5. "bufio"
  6. "context"
  7. "fmt"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "runtime/debug"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/containerd/cgroups"
  18. statsV1 "github.com/containerd/cgroups/stats/v1"
  19. statsV2 "github.com/containerd/cgroups/v2/stats"
  20. "github.com/containerd/containerd/pkg/userns"
  21. "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/blkiodev"
  23. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  24. containertypes "github.com/docker/docker/api/types/container"
  25. "github.com/docker/docker/container"
  26. "github.com/docker/docker/daemon/config"
  27. "github.com/docker/docker/daemon/initlayer"
  28. "github.com/docker/docker/errdefs"
  29. "github.com/docker/docker/libcontainerd/remote"
  30. "github.com/docker/docker/libnetwork"
  31. nwconfig "github.com/docker/docker/libnetwork/config"
  32. "github.com/docker/docker/libnetwork/drivers/bridge"
  33. "github.com/docker/docker/libnetwork/netlabel"
  34. "github.com/docker/docker/libnetwork/netutils"
  35. "github.com/docker/docker/libnetwork/options"
  36. lntypes "github.com/docker/docker/libnetwork/types"
  37. "github.com/docker/docker/opts"
  38. "github.com/docker/docker/pkg/containerfs"
  39. "github.com/docker/docker/pkg/idtools"
  40. "github.com/docker/docker/pkg/parsers"
  41. "github.com/docker/docker/pkg/parsers/kernel"
  42. "github.com/docker/docker/pkg/sysinfo"
  43. "github.com/docker/docker/runconfig"
  44. volumemounts "github.com/docker/docker/volume/mounts"
  45. "github.com/moby/sys/mount"
  46. specs "github.com/opencontainers/runtime-spec/specs-go"
  47. "github.com/opencontainers/selinux/go-selinux"
  48. "github.com/opencontainers/selinux/go-selinux/label"
  49. "github.com/pkg/errors"
  50. "github.com/sirupsen/logrus"
  51. "github.com/vishvananda/netlink"
  52. "golang.org/x/sys/unix"
  53. )
  54. const (
  55. isWindows = false
  56. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  57. linuxMinCPUShares = 2
  58. linuxMaxCPUShares = 262144
  59. platformSupported = true
  60. // It's not kernel limit, we want this 6M limit to account for overhead during startup, and to supply a reasonable functional container
  61. linuxMinMemory = 6291456
  62. // constants for remapped root settings
  63. defaultIDSpecifier = "default"
  64. defaultRemappedID = "dockremap"
  65. // constant for cgroup drivers
  66. cgroupFsDriver = "cgroupfs"
  67. cgroupSystemdDriver = "systemd"
  68. cgroupNoneDriver = "none"
  69. )
  70. type containerGetter interface {
  71. GetContainer(string) (*container.Container, error)
  72. }
  73. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  74. memory := specs.LinuxMemory{}
  75. if config.Memory > 0 {
  76. memory.Limit = &config.Memory
  77. }
  78. if config.MemoryReservation > 0 {
  79. memory.Reservation = &config.MemoryReservation
  80. }
  81. if config.MemorySwap > 0 {
  82. memory.Swap = &config.MemorySwap
  83. }
  84. if config.MemorySwappiness != nil {
  85. swappiness := uint64(*config.MemorySwappiness)
  86. memory.Swappiness = &swappiness
  87. }
  88. if config.OomKillDisable != nil {
  89. memory.DisableOOMKiller = config.OomKillDisable
  90. }
  91. if config.KernelMemory != 0 {
  92. memory.Kernel = &config.KernelMemory
  93. }
  94. if config.KernelMemoryTCP != 0 {
  95. memory.KernelTCP = &config.KernelMemoryTCP
  96. }
  97. return &memory
  98. }
  99. func getPidsLimit(config containertypes.Resources) *specs.LinuxPids {
  100. if config.PidsLimit == nil {
  101. return nil
  102. }
  103. if *config.PidsLimit <= 0 {
  104. // docker API allows 0 and negative values to unset this to be consistent
  105. // with default values. When updating values, runc requires -1 to unset
  106. // the previous limit.
  107. return &specs.LinuxPids{Limit: -1}
  108. }
  109. return &specs.LinuxPids{Limit: *config.PidsLimit}
  110. }
  111. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  112. cpu := specs.LinuxCPU{}
  113. if config.CPUShares < 0 {
  114. return nil, fmt.Errorf("shares: invalid argument")
  115. }
  116. if config.CPUShares >= 0 {
  117. shares := uint64(config.CPUShares)
  118. cpu.Shares = &shares
  119. }
  120. if config.CpusetCpus != "" {
  121. cpu.Cpus = config.CpusetCpus
  122. }
  123. if config.CpusetMems != "" {
  124. cpu.Mems = config.CpusetMems
  125. }
  126. if config.NanoCPUs > 0 {
  127. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  128. period := uint64(100 * time.Millisecond / time.Microsecond)
  129. quota := config.NanoCPUs * int64(period) / 1e9
  130. cpu.Period = &period
  131. cpu.Quota = &quota
  132. }
  133. if config.CPUPeriod != 0 {
  134. period := uint64(config.CPUPeriod)
  135. cpu.Period = &period
  136. }
  137. if config.CPUQuota != 0 {
  138. q := config.CPUQuota
  139. cpu.Quota = &q
  140. }
  141. if config.CPURealtimePeriod != 0 {
  142. period := uint64(config.CPURealtimePeriod)
  143. cpu.RealtimePeriod = &period
  144. }
  145. if config.CPURealtimeRuntime != 0 {
  146. c := config.CPURealtimeRuntime
  147. cpu.RealtimeRuntime = &c
  148. }
  149. return &cpu, nil
  150. }
  151. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  152. var stat unix.Stat_t
  153. var blkioWeightDevices []specs.LinuxWeightDevice
  154. for _, weightDevice := range config.BlkioWeightDevice {
  155. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  156. return nil, errors.WithStack(&os.PathError{Op: "stat", Path: weightDevice.Path, Err: err})
  157. }
  158. weight := weightDevice.Weight
  159. d := specs.LinuxWeightDevice{Weight: &weight}
  160. // The type is 32bit on mips.
  161. d.Major = int64(unix.Major(uint64(stat.Rdev))) //nolint: unconvert
  162. d.Minor = int64(unix.Minor(uint64(stat.Rdev))) //nolint: unconvert
  163. blkioWeightDevices = append(blkioWeightDevices, d)
  164. }
  165. return blkioWeightDevices, nil
  166. }
  167. func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfig *containertypes.HostConfig) error {
  168. container.NoNewPrivileges = daemon.configStore.NoNewPrivileges
  169. return parseSecurityOpt(container, hostConfig)
  170. }
  171. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  172. var (
  173. labelOpts []string
  174. err error
  175. )
  176. for _, opt := range config.SecurityOpt {
  177. if opt == "no-new-privileges" {
  178. container.NoNewPrivileges = true
  179. continue
  180. }
  181. if opt == "disable" {
  182. labelOpts = append(labelOpts, "disable")
  183. continue
  184. }
  185. var con []string
  186. if strings.Contains(opt, "=") {
  187. con = strings.SplitN(opt, "=", 2)
  188. } else if strings.Contains(opt, ":") {
  189. con = strings.SplitN(opt, ":", 2)
  190. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  191. }
  192. if len(con) != 2 {
  193. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  194. }
  195. switch con[0] {
  196. case "label":
  197. labelOpts = append(labelOpts, con[1])
  198. case "apparmor":
  199. container.AppArmorProfile = con[1]
  200. case "seccomp":
  201. container.SeccompProfile = con[1]
  202. case "no-new-privileges":
  203. noNewPrivileges, err := strconv.ParseBool(con[1])
  204. if err != nil {
  205. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  206. }
  207. container.NoNewPrivileges = noNewPrivileges
  208. default:
  209. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  210. }
  211. }
  212. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  213. return err
  214. }
  215. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.LinuxThrottleDevice, error) {
  216. var throttleDevices []specs.LinuxThrottleDevice
  217. var stat unix.Stat_t
  218. for _, d := range devs {
  219. if err := unix.Stat(d.Path, &stat); err != nil {
  220. return nil, errors.WithStack(&os.PathError{Op: "stat", Path: d.Path, Err: err})
  221. }
  222. d := specs.LinuxThrottleDevice{Rate: d.Rate}
  223. // the type is 32bit on mips
  224. d.Major = int64(unix.Major(uint64(stat.Rdev))) //nolint: unconvert
  225. d.Minor = int64(unix.Minor(uint64(stat.Rdev))) //nolint: unconvert
  226. throttleDevices = append(throttleDevices, d)
  227. }
  228. return throttleDevices, nil
  229. }
  230. // adjustParallelLimit takes a number of objects and a proposed limit and
  231. // figures out if it's reasonable (and adjusts it accordingly). This is only
  232. // used for daemon startup, which does a lot of parallel loading of containers
  233. // (and if we exceed RLIMIT_NOFILE then we're in trouble).
  234. func adjustParallelLimit(n int, limit int) int {
  235. // Rule-of-thumb overhead factor (how many files will each goroutine open
  236. // simultaneously). Yes, this is ugly but to be frank this whole thing is
  237. // ugly.
  238. const overhead = 2
  239. // On Linux, we need to ensure that parallelStartupJobs doesn't cause us to
  240. // exceed RLIMIT_NOFILE. If parallelStartupJobs is too large, we reduce it
  241. // and give a warning (since in theory the user should increase their
  242. // ulimits to the largest possible value for dockerd).
  243. var rlim unix.Rlimit
  244. if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlim); err != nil {
  245. logrus.Warnf("Couldn't find dockerd's RLIMIT_NOFILE to double-check startup parallelism factor: %v", err)
  246. return limit
  247. }
  248. softRlimit := int(rlim.Cur)
  249. // Much fewer containers than RLIMIT_NOFILE. No need to adjust anything.
  250. if softRlimit > overhead*n {
  251. return limit
  252. }
  253. // RLIMIT_NOFILE big enough, no need to adjust anything.
  254. if softRlimit > overhead*limit {
  255. return limit
  256. }
  257. logrus.Warnf("Found dockerd's open file ulimit (%v) is far too small -- consider increasing it significantly (at least %v)", softRlimit, overhead*limit)
  258. return softRlimit / overhead
  259. }
  260. func checkKernel() error {
  261. // Check for unsupported kernel versions
  262. // FIXME: it would be cleaner to not test for specific versions, but rather
  263. // test for specific functionalities.
  264. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  265. // without actually causing a kernel panic, so we need this workaround until
  266. // the circumstances of pre-3.10 crashes are clearer.
  267. // For details see https://github.com/docker/docker/issues/407
  268. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  269. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  270. if !kernel.CheckKernelVersion(3, 10, 0) {
  271. v, _ := kernel.GetKernelVersion()
  272. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  273. logrus.Fatalf("Your Linux kernel version %s is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.", v.String())
  274. }
  275. }
  276. return nil
  277. }
  278. // adaptContainerSettings is called during container creation to modify any
  279. // settings necessary in the HostConfig structure.
  280. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  281. if adjustCPUShares && hostConfig.CPUShares > 0 {
  282. // Handle unsupported CPUShares
  283. if hostConfig.CPUShares < linuxMinCPUShares {
  284. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  285. hostConfig.CPUShares = linuxMinCPUShares
  286. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  287. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  288. hostConfig.CPUShares = linuxMaxCPUShares
  289. }
  290. }
  291. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  292. // By default, MemorySwap is set to twice the size of Memory.
  293. hostConfig.MemorySwap = hostConfig.Memory * 2
  294. }
  295. if hostConfig.ShmSize == 0 {
  296. hostConfig.ShmSize = config.DefaultShmSize
  297. if daemon.configStore != nil {
  298. hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
  299. }
  300. }
  301. // Set default IPC mode, if unset for container
  302. if hostConfig.IpcMode.IsEmpty() {
  303. m := config.DefaultIpcMode
  304. if daemon.configStore != nil {
  305. m = containertypes.IpcMode(daemon.configStore.IpcMode)
  306. }
  307. hostConfig.IpcMode = m
  308. }
  309. // Set default cgroup namespace mode, if unset for container
  310. if hostConfig.CgroupnsMode.IsEmpty() {
  311. // for cgroup v2: unshare cgroupns even for privileged containers
  312. // https://github.com/containers/libpod/pull/4374#issuecomment-549776387
  313. if hostConfig.Privileged && cgroups.Mode() != cgroups.Unified {
  314. hostConfig.CgroupnsMode = containertypes.CgroupnsModeHost
  315. } else {
  316. m := containertypes.CgroupnsModeHost
  317. if cgroups.Mode() == cgroups.Unified {
  318. m = containertypes.CgroupnsModePrivate
  319. }
  320. if daemon.configStore != nil {
  321. m = containertypes.CgroupnsMode(daemon.configStore.CgroupNamespaceMode)
  322. }
  323. hostConfig.CgroupnsMode = m
  324. }
  325. }
  326. adaptSharedNamespaceContainer(daemon, hostConfig)
  327. var err error
  328. secOpts, err := daemon.generateSecurityOpt(hostConfig)
  329. if err != nil {
  330. return err
  331. }
  332. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, secOpts...)
  333. if hostConfig.OomKillDisable == nil {
  334. defaultOomKillDisable := false
  335. hostConfig.OomKillDisable = &defaultOomKillDisable
  336. }
  337. return nil
  338. }
  339. // adaptSharedNamespaceContainer replaces container name with its ID in hostConfig.
  340. // To be more precisely, it modifies `container:name` to `container:ID` of PidMode, IpcMode
  341. // and NetworkMode.
  342. //
  343. // When a container shares its namespace with another container, use ID can keep the namespace
  344. // sharing connection between the two containers even the another container is renamed.
  345. func adaptSharedNamespaceContainer(daemon containerGetter, hostConfig *containertypes.HostConfig) {
  346. containerPrefix := "container:"
  347. if hostConfig.PidMode.IsContainer() {
  348. pidContainer := hostConfig.PidMode.Container()
  349. // if there is any error returned here, we just ignore it and leave it to be
  350. // handled in the following logic
  351. if c, err := daemon.GetContainer(pidContainer); err == nil {
  352. hostConfig.PidMode = containertypes.PidMode(containerPrefix + c.ID)
  353. }
  354. }
  355. if hostConfig.IpcMode.IsContainer() {
  356. ipcContainer := hostConfig.IpcMode.Container()
  357. if c, err := daemon.GetContainer(ipcContainer); err == nil {
  358. hostConfig.IpcMode = containertypes.IpcMode(containerPrefix + c.ID)
  359. }
  360. }
  361. if hostConfig.NetworkMode.IsContainer() {
  362. netContainer := hostConfig.NetworkMode.ConnectedContainer()
  363. if c, err := daemon.GetContainer(netContainer); err == nil {
  364. hostConfig.NetworkMode = containertypes.NetworkMode(containerPrefix + c.ID)
  365. }
  366. }
  367. }
  368. // verifyPlatformContainerResources performs platform-specific validation of the container's resource-configuration
  369. func verifyPlatformContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) (warnings []string, err error) {
  370. fixMemorySwappiness(resources)
  371. // memory subsystem checks and adjustments
  372. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  373. return warnings, fmt.Errorf("Minimum memory limit allowed is 6MB")
  374. }
  375. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  376. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  377. resources.Memory = 0
  378. resources.MemorySwap = -1
  379. }
  380. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  381. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  382. resources.MemorySwap = -1
  383. }
  384. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  385. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  386. }
  387. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  388. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  389. }
  390. if resources.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
  391. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  392. resources.MemorySwappiness = nil
  393. }
  394. if resources.MemorySwappiness != nil {
  395. swappiness := *resources.MemorySwappiness
  396. if swappiness < 0 || swappiness > 100 {
  397. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  398. }
  399. }
  400. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  401. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  402. resources.MemoryReservation = 0
  403. }
  404. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  405. return warnings, fmt.Errorf("Minimum memory reservation allowed is 6MB")
  406. }
  407. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  408. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  409. }
  410. if resources.KernelMemory > 0 {
  411. // Kernel memory limit is not supported on cgroup v2.
  412. // Even on cgroup v1, kernel memory limit (`kmem.limit_in_bytes`) has been deprecated since kernel 5.4.
  413. // https://github.com/torvalds/linux/commit/0158115f702b0ba208ab0b5adf44cae99b3ebcc7
  414. warnings = append(warnings, "Specifying a kernel memory limit is deprecated and will be removed in a future release.")
  415. }
  416. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  417. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  418. resources.KernelMemory = 0
  419. }
  420. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  421. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  422. }
  423. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  424. 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.")
  425. }
  426. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  427. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  428. // warning the caller if they already wanted the feature to be off
  429. if *resources.OomKillDisable {
  430. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  431. }
  432. resources.OomKillDisable = nil
  433. }
  434. if resources.OomKillDisable != nil && *resources.OomKillDisable && resources.Memory == 0 {
  435. 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.")
  436. }
  437. if resources.PidsLimit != nil && !sysInfo.PidsLimit {
  438. if *resources.PidsLimit > 0 {
  439. warnings = append(warnings, "Your kernel does not support PIDs limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  440. }
  441. resources.PidsLimit = nil
  442. }
  443. // cpu subsystem checks and adjustments
  444. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  445. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  446. }
  447. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  448. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  449. }
  450. if resources.NanoCPUs > 0 && !sysInfo.CPUCfs {
  451. return warnings, fmt.Errorf("NanoCPUs can not be set, as your kernel does not support CPU CFS scheduler or the cgroup is not mounted")
  452. }
  453. // The highest precision we could get on Linux is 0.001, by setting
  454. // cpu.cfs_period_us=1000ms
  455. // cpu.cfs_quota=1ms
  456. // See the following link for details:
  457. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  458. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  459. // The error message is 0.01 so that this is consistent with Windows
  460. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  461. 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())
  462. }
  463. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  464. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  465. resources.CPUShares = 0
  466. }
  467. if (resources.CPUPeriod != 0 || resources.CPUQuota != 0) && !sysInfo.CPUCfs {
  468. warnings = append(warnings, "Your kernel does not support CPU CFS scheduler. CPU period/quota discarded.")
  469. resources.CPUPeriod = 0
  470. resources.CPUQuota = 0
  471. }
  472. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  473. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  474. }
  475. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  476. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  477. }
  478. if resources.CPUPercent > 0 {
  479. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  480. resources.CPUPercent = 0
  481. }
  482. // cpuset subsystem checks and adjustments
  483. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  484. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  485. resources.CpusetCpus = ""
  486. resources.CpusetMems = ""
  487. }
  488. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  489. if err != nil {
  490. return warnings, errors.Wrapf(err, "Invalid value %s for cpuset cpus", resources.CpusetCpus)
  491. }
  492. if !cpusAvailable {
  493. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  494. }
  495. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  496. if err != nil {
  497. return warnings, errors.Wrapf(err, "Invalid value %s for cpuset mems", resources.CpusetMems)
  498. }
  499. if !memsAvailable {
  500. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  501. }
  502. // blkio subsystem checks and adjustments
  503. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  504. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  505. resources.BlkioWeight = 0
  506. }
  507. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  508. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  509. }
  510. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  511. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  512. }
  513. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  514. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  515. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  516. }
  517. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  518. 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.")
  519. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  520. }
  521. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  522. 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.")
  523. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  524. }
  525. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  526. 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.")
  527. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  528. }
  529. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  530. 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.")
  531. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  532. }
  533. return warnings, nil
  534. }
  535. func (daemon *Daemon) getCgroupDriver() string {
  536. if UsingSystemd(daemon.configStore) {
  537. return cgroupSystemdDriver
  538. }
  539. if daemon.Rootless() {
  540. return cgroupNoneDriver
  541. }
  542. return cgroupFsDriver
  543. }
  544. // getCD gets the raw value of the native.cgroupdriver option, if set.
  545. func getCD(config *config.Config) string {
  546. for _, option := range config.ExecOptions {
  547. key, val, err := parsers.ParseKeyValueOpt(option)
  548. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  549. continue
  550. }
  551. return val
  552. }
  553. return ""
  554. }
  555. // verifyCgroupDriver validates native.cgroupdriver
  556. func verifyCgroupDriver(config *config.Config) error {
  557. cd := getCD(config)
  558. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  559. return nil
  560. }
  561. if cd == cgroupNoneDriver {
  562. return fmt.Errorf("native.cgroupdriver option %s is internally used and cannot be specified manually", cd)
  563. }
  564. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  565. }
  566. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  567. func UsingSystemd(config *config.Config) bool {
  568. if getCD(config) == cgroupSystemdDriver {
  569. return true
  570. }
  571. // On cgroup v2 hosts, default to systemd driver
  572. if getCD(config) == "" && cgroups.Mode() == cgroups.Unified && isRunningSystemd() {
  573. return true
  574. }
  575. return false
  576. }
  577. var (
  578. runningSystemd bool
  579. detectSystemd sync.Once
  580. )
  581. // isRunningSystemd checks whether the host was booted with systemd as its init
  582. // system. This functions similarly to systemd's `sd_booted(3)`: internally, it
  583. // checks whether /run/systemd/system/ exists and is a directory.
  584. // http://www.freedesktop.org/software/systemd/man/sd_booted.html
  585. //
  586. // NOTE: This function comes from package github.com/coreos/go-systemd/util
  587. // It was borrowed here to avoid a dependency on cgo.
  588. func isRunningSystemd() bool {
  589. detectSystemd.Do(func() {
  590. fi, err := os.Lstat("/run/systemd/system")
  591. if err != nil {
  592. return
  593. }
  594. runningSystemd = fi.IsDir()
  595. })
  596. return runningSystemd
  597. }
  598. // verifyPlatformContainerSettings performs platform-specific validation of the
  599. // hostconfig and config structures.
  600. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, update bool) (warnings []string, err error) {
  601. if hostConfig == nil {
  602. return nil, nil
  603. }
  604. sysInfo := daemon.RawSysInfo()
  605. w, err := verifyPlatformContainerResources(&hostConfig.Resources, sysInfo, update)
  606. // no matter err is nil or not, w could have data in itself.
  607. warnings = append(warnings, w...)
  608. if err != nil {
  609. return warnings, err
  610. }
  611. if hostConfig.ShmSize < 0 {
  612. return warnings, fmt.Errorf("SHM size can not be less than 0")
  613. }
  614. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  615. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  616. }
  617. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  618. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  619. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  620. }
  621. if hostConfig.NetworkMode.IsHost() && len(hostConfig.PortBindings) > 0 {
  622. warnings = append(warnings, "Published ports are discarded when using host network mode")
  623. }
  624. // check for various conflicting options with user namespaces
  625. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  626. if hostConfig.Privileged {
  627. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  628. }
  629. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  630. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  631. }
  632. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  633. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  634. }
  635. }
  636. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  637. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  638. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  639. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  640. }
  641. }
  642. if hostConfig.Runtime == "" {
  643. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  644. }
  645. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  646. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  647. }
  648. parser := volumemounts.NewParser()
  649. for dest := range hostConfig.Tmpfs {
  650. if err := parser.ValidateTmpfsMountDestination(dest); err != nil {
  651. return warnings, err
  652. }
  653. }
  654. if !hostConfig.CgroupnsMode.Valid() {
  655. return warnings, fmt.Errorf("invalid cgroup namespace mode: %v", hostConfig.CgroupnsMode)
  656. }
  657. if hostConfig.CgroupnsMode.IsPrivate() {
  658. if !sysInfo.CgroupNamespaces {
  659. warnings = append(warnings, "Your kernel does not support cgroup namespaces. Cgroup namespace setting discarded.")
  660. }
  661. }
  662. if hostConfig.Runtime == config.LinuxV1RuntimeName || (hostConfig.Runtime == "" && daemon.configStore.DefaultRuntime == config.LinuxV1RuntimeName) {
  663. warnings = append(warnings, fmt.Sprintf("Configured runtime %q is deprecated and will be removed in the next release.", config.LinuxV1RuntimeName))
  664. }
  665. return warnings, nil
  666. }
  667. // verifyDaemonSettings performs validation of daemon config struct
  668. func verifyDaemonSettings(conf *config.Config) error {
  669. if conf.ContainerdNamespace == conf.ContainerdPluginNamespace {
  670. return errors.New("containers namespace and plugins namespace cannot be the same")
  671. }
  672. // Check for mutually incompatible config options
  673. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  674. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  675. }
  676. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  677. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  678. }
  679. if conf.BridgeConfig.EnableIP6Tables && !conf.Experimental {
  680. return fmt.Errorf("ip6tables rules are only available if experimental features are enabled")
  681. }
  682. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  683. conf.BridgeConfig.EnableIPMasq = false
  684. }
  685. if err := verifyCgroupDriver(conf); err != nil {
  686. return err
  687. }
  688. if conf.CgroupParent != "" && UsingSystemd(conf) {
  689. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  690. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  691. }
  692. }
  693. if conf.Rootless && UsingSystemd(conf) && cgroups.Mode() != cgroups.Unified {
  694. return fmt.Errorf("exec-opt native.cgroupdriver=systemd requires cgroup v2 for rootless mode")
  695. }
  696. configureRuntimes(conf)
  697. if rtName := conf.GetDefaultRuntimeName(); rtName != "" {
  698. if conf.GetRuntime(rtName) == nil {
  699. return fmt.Errorf("specified default runtime '%s' does not exist", rtName)
  700. }
  701. if rtName == config.LinuxV1RuntimeName {
  702. logrus.Warnf("Configured default runtime %q is deprecated and will be removed in the next release.", config.LinuxV1RuntimeName)
  703. }
  704. }
  705. return nil
  706. }
  707. // checkSystem validates platform-specific requirements
  708. func checkSystem() error {
  709. return checkKernel()
  710. }
  711. // configureMaxThreads sets the Go runtime max threads threshold
  712. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  713. func configureMaxThreads(config *config.Config) error {
  714. mt, err := os.ReadFile("/proc/sys/kernel/threads-max")
  715. if err != nil {
  716. return err
  717. }
  718. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  719. if err != nil {
  720. return err
  721. }
  722. maxThreads := (mtint / 100) * 90
  723. debug.SetMaxThreads(maxThreads)
  724. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  725. return nil
  726. }
  727. func overlaySupportsSelinux() (bool, error) {
  728. f, err := os.Open("/proc/kallsyms")
  729. if err != nil {
  730. if os.IsNotExist(err) {
  731. return false, nil
  732. }
  733. return false, err
  734. }
  735. defer f.Close()
  736. s := bufio.NewScanner(f)
  737. for s.Scan() {
  738. if strings.HasSuffix(s.Text(), " security_inode_copy_up") {
  739. return true, nil
  740. }
  741. }
  742. return false, s.Err()
  743. }
  744. // configureKernelSecuritySupport configures and validates security support for the kernel
  745. func configureKernelSecuritySupport(config *config.Config, driverName string) error {
  746. if config.EnableSelinuxSupport {
  747. if !selinux.GetEnabled() {
  748. logrus.Warn("Docker could not enable SELinux on the host system")
  749. return nil
  750. }
  751. if driverName == "overlay" || driverName == "overlay2" {
  752. // If driver is overlay or overlay2, make sure kernel
  753. // supports selinux with overlay.
  754. supported, err := overlaySupportsSelinux()
  755. if err != nil {
  756. return err
  757. }
  758. if !supported {
  759. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverName)
  760. }
  761. }
  762. } else {
  763. selinux.SetDisabled()
  764. }
  765. return nil
  766. }
  767. func (daemon *Daemon) initNetworkController(config *config.Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  768. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  769. if err != nil {
  770. return nil, err
  771. }
  772. controller, err := libnetwork.New(netOptions...)
  773. if err != nil {
  774. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  775. }
  776. if len(activeSandboxes) > 0 {
  777. logrus.Info("There are old running containers, the network config will not take affect")
  778. return controller, nil
  779. }
  780. // Initialize default network on "null"
  781. if n, _ := controller.NetworkByName("none"); n == nil {
  782. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  783. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  784. }
  785. }
  786. // Initialize default network on "host"
  787. if n, _ := controller.NetworkByName("host"); n == nil {
  788. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  789. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  790. }
  791. }
  792. // Clear stale bridge network
  793. if n, err := controller.NetworkByName("bridge"); err == nil {
  794. if err = n.Delete(); err != nil {
  795. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  796. }
  797. if len(config.NetworkConfig.DefaultAddressPools.Value()) > 0 && !daemon.configStore.LiveRestoreEnabled {
  798. removeDefaultBridgeInterface()
  799. }
  800. }
  801. if !config.DisableBridge {
  802. // Initialize default driver "bridge"
  803. if err := initBridgeDriver(controller, config); err != nil {
  804. return nil, err
  805. }
  806. } else {
  807. removeDefaultBridgeInterface()
  808. }
  809. // Set HostGatewayIP to the default bridge's IP if it is empty
  810. if daemon.configStore.HostGatewayIP == nil && controller != nil {
  811. if n, err := controller.NetworkByName("bridge"); err == nil {
  812. v4Info, v6Info := n.Info().IpamInfo()
  813. var gateway net.IP
  814. if len(v4Info) > 0 {
  815. gateway = v4Info[0].Gateway.IP
  816. } else if len(v6Info) > 0 {
  817. gateway = v6Info[0].Gateway.IP
  818. }
  819. daemon.configStore.HostGatewayIP = gateway
  820. }
  821. }
  822. return controller, nil
  823. }
  824. func driverOptions(config *config.Config) []nwconfig.Option {
  825. bridgeConfig := options.Generic{
  826. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  827. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  828. "EnableIP6Tables": config.BridgeConfig.EnableIP6Tables,
  829. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  830. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath}
  831. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  832. dOptions := []nwconfig.Option{}
  833. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  834. return dOptions
  835. }
  836. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  837. bridgeName := bridge.DefaultBridgeName
  838. if config.BridgeConfig.Iface != "" {
  839. bridgeName = config.BridgeConfig.Iface
  840. }
  841. netOption := map[string]string{
  842. bridge.BridgeName: bridgeName,
  843. bridge.DefaultBridge: strconv.FormatBool(true),
  844. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  845. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  846. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  847. }
  848. // --ip processing
  849. if config.BridgeConfig.DefaultIP != nil {
  850. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  851. }
  852. ipamV4Conf := &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  853. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  854. if err != nil {
  855. return errors.Wrap(err, "list bridge addresses failed")
  856. }
  857. nw := nwList[0]
  858. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  859. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  860. if err != nil {
  861. return errors.Wrap(err, "parse CIDR failed")
  862. }
  863. // Iterate through in case there are multiple addresses for the bridge
  864. for _, entry := range nwList {
  865. if fCIDR.Contains(entry.IP) {
  866. nw = entry
  867. break
  868. }
  869. }
  870. }
  871. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  872. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  873. if hip.IsGlobalUnicast() {
  874. ipamV4Conf.Gateway = nw.IP.String()
  875. }
  876. if config.BridgeConfig.IP != "" {
  877. ip, ipNet, err := net.ParseCIDR(config.BridgeConfig.IP)
  878. if err != nil {
  879. return err
  880. }
  881. ipamV4Conf.PreferredPool = ipNet.String()
  882. ipamV4Conf.Gateway = ip.String()
  883. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  884. logrus.Infof("Default bridge (%s) is assigned with an IP address %s. Daemon option --bip can be used to set a preferred IP address", bridgeName, ipamV4Conf.PreferredPool)
  885. }
  886. if config.BridgeConfig.FixedCIDR != "" {
  887. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  888. if err != nil {
  889. return err
  890. }
  891. ipamV4Conf.SubPool = fCIDR.String()
  892. }
  893. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  894. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  895. }
  896. var (
  897. deferIPv6Alloc bool
  898. ipamV6Conf *libnetwork.IpamConf
  899. )
  900. if config.BridgeConfig.EnableIPv6 && config.BridgeConfig.FixedCIDRv6 == "" {
  901. 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"))
  902. } else if config.BridgeConfig.FixedCIDRv6 != "" {
  903. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  904. if err != nil {
  905. return err
  906. }
  907. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  908. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  909. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  910. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  911. // on this network until after the driver has created the endpoint and returned the
  912. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  913. ones, _ := fCIDRv6.Mask.Size()
  914. deferIPv6Alloc = ones <= 80
  915. ipamV6Conf = &libnetwork.IpamConf{
  916. AuxAddresses: make(map[string]string),
  917. PreferredPool: fCIDRv6.String(),
  918. }
  919. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  920. // address belongs to the same network, we need to inform libnetwork about it, so
  921. // that it can be reserved with IPAM and it will not be given away to somebody else
  922. for _, nw6 := range nw6List {
  923. if fCIDRv6.Contains(nw6.IP) {
  924. ipamV6Conf.Gateway = nw6.IP.String()
  925. break
  926. }
  927. }
  928. }
  929. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  930. if ipamV6Conf == nil {
  931. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  932. }
  933. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  934. }
  935. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  936. v6Conf := []*libnetwork.IpamConf{}
  937. if ipamV6Conf != nil {
  938. v6Conf = append(v6Conf, ipamV6Conf)
  939. }
  940. // Initialize default network on "bridge" with the same name
  941. _, err = controller.NewNetwork("bridge", "bridge", "",
  942. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  943. libnetwork.NetworkOptionDriverOpts(netOption),
  944. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  945. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  946. if err != nil {
  947. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  948. }
  949. return nil
  950. }
  951. // Remove default bridge interface if present (--bridge=none use case)
  952. func removeDefaultBridgeInterface() {
  953. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  954. if err := netlink.LinkDel(lnk); err != nil {
  955. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  956. }
  957. }
  958. }
  959. func setupInitLayer(idMapping *idtools.IdentityMapping) func(containerfs.ContainerFS) error {
  960. return func(initPath containerfs.ContainerFS) error {
  961. return initlayer.Setup(initPath, idMapping.RootPair())
  962. }
  963. }
  964. // Parse the remapped root (user namespace) option, which can be one of:
  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 nil, 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 nil, 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. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  1067. return &idtools.IdentityMapping{}, nil
  1068. }
  1069. logrus.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.NewIdentityMapping(username)
  1073. if err != nil {
  1074. return nil, 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, 0711); 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, 0711); 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, 0710, 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. logrus.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, 0710, 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 !idtools.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. logrus.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. func setupDaemonRootPropagation(cfg *config.Config) error {
  1136. rootParentMount, mountOptions, err := getSourceMount(cfg.Root)
  1137. if err != nil {
  1138. return errors.Wrap(err, "error getting daemon root's parent mount")
  1139. }
  1140. var cleanupOldFile bool
  1141. cleanupFile := getUnmountOnShutdownPath(cfg)
  1142. defer func() {
  1143. if !cleanupOldFile {
  1144. return
  1145. }
  1146. if err := os.Remove(cleanupFile); err != nil && !os.IsNotExist(err) {
  1147. logrus.WithError(err).WithField("file", cleanupFile).Warn("could not clean up old root propagation unmount file")
  1148. }
  1149. }()
  1150. if hasMountInfoOption(mountOptions, sharedPropagationOption, slavePropagationOption) {
  1151. cleanupOldFile = true
  1152. return nil
  1153. }
  1154. if err := mount.MakeShared(cfg.Root); err != nil {
  1155. return errors.Wrap(err, "could not setup daemon root propagation to shared")
  1156. }
  1157. // check the case where this may have already been a mount to itself.
  1158. // If so then the daemon only performed a remount and should not try to unmount this later.
  1159. if rootParentMount == cfg.Root {
  1160. cleanupOldFile = true
  1161. return nil
  1162. }
  1163. if err := os.MkdirAll(filepath.Dir(cleanupFile), 0700); err != nil {
  1164. return errors.Wrap(err, "error creating dir to store mount cleanup file")
  1165. }
  1166. if err := os.WriteFile(cleanupFile, nil, 0600); err != nil {
  1167. return errors.Wrap(err, "error writing file to signal mount cleanup on shutdown")
  1168. }
  1169. return nil
  1170. }
  1171. // getUnmountOnShutdownPath generates the path to used when writing the file that signals to the daemon that on shutdown
  1172. // the daemon root should be unmounted.
  1173. func getUnmountOnShutdownPath(config *config.Config) string {
  1174. return filepath.Join(config.ExecRoot, "unmount-on-shutdown")
  1175. }
  1176. // registerLinks writes the links to a file.
  1177. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1178. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1179. return nil
  1180. }
  1181. for _, l := range hostConfig.Links {
  1182. name, alias, err := opts.ParseLink(l)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. child, err := daemon.GetContainer(name)
  1187. if err != nil {
  1188. if errdefs.IsNotFound(err) {
  1189. // Trying to link to a non-existing container is not valid, and
  1190. // should return an "invalid parameter" error. Returning a "not
  1191. // found" error here would make the client report the container's
  1192. // image could not be found (see moby/moby#39823)
  1193. err = errdefs.InvalidParameter(err)
  1194. }
  1195. return errors.Wrapf(err, "could not get container for %s", name)
  1196. }
  1197. for child.HostConfig.NetworkMode.IsContainer() {
  1198. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  1199. child, err = daemon.GetContainer(parts[1])
  1200. if err != nil {
  1201. if errdefs.IsNotFound(err) {
  1202. // Trying to link to a non-existing container is not valid, and
  1203. // should return an "invalid parameter" error. Returning a "not
  1204. // found" error here would make the client report the container's
  1205. // image could not be found (see moby/moby#39823)
  1206. err = errdefs.InvalidParameter(err)
  1207. }
  1208. return errors.Wrapf(err, "Could not get container for %s", parts[1])
  1209. }
  1210. }
  1211. if child.HostConfig.NetworkMode.IsHost() {
  1212. return runconfig.ErrConflictHostNetworkAndLinks
  1213. }
  1214. if err := daemon.registerLink(container, child, alias); err != nil {
  1215. return err
  1216. }
  1217. }
  1218. // After we load all the links into the daemon
  1219. // set them to nil on the hostconfig
  1220. _, err := container.WriteHostConfig()
  1221. return err
  1222. }
  1223. // conditionalMountOnStart is a platform specific helper function during the
  1224. // container start to call mount.
  1225. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1226. return daemon.Mount(container)
  1227. }
  1228. // conditionalUnmountOnCleanup is a platform specific helper function called
  1229. // during the cleanup of a container to unmount.
  1230. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1231. return daemon.Unmount(container)
  1232. }
  1233. func copyBlkioEntry(entries []*statsV1.BlkIOEntry) []types.BlkioStatEntry {
  1234. out := make([]types.BlkioStatEntry, len(entries))
  1235. for i, re := range entries {
  1236. out[i] = types.BlkioStatEntry{
  1237. Major: re.Major,
  1238. Minor: re.Minor,
  1239. Op: re.Op,
  1240. Value: re.Value,
  1241. }
  1242. }
  1243. return out
  1244. }
  1245. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1246. if !c.IsRunning() {
  1247. return nil, errNotRunning(c.ID)
  1248. }
  1249. cs, err := daemon.containerd.Stats(context.Background(), c.ID)
  1250. if err != nil {
  1251. if strings.Contains(err.Error(), "container not found") {
  1252. return nil, containerNotFound(c.ID)
  1253. }
  1254. return nil, err
  1255. }
  1256. s := &types.StatsJSON{}
  1257. s.Read = cs.Read
  1258. stats := cs.Metrics
  1259. switch t := stats.(type) {
  1260. case *statsV1.Metrics:
  1261. return daemon.statsV1(s, t)
  1262. case *statsV2.Metrics:
  1263. return daemon.statsV2(s, t)
  1264. default:
  1265. return nil, errors.Errorf("unexpected type of metrics %+v", t)
  1266. }
  1267. }
  1268. func (daemon *Daemon) statsV1(s *types.StatsJSON, stats *statsV1.Metrics) (*types.StatsJSON, error) {
  1269. if stats.Blkio != nil {
  1270. s.BlkioStats = types.BlkioStats{
  1271. IoServiceBytesRecursive: copyBlkioEntry(stats.Blkio.IoServiceBytesRecursive),
  1272. IoServicedRecursive: copyBlkioEntry(stats.Blkio.IoServicedRecursive),
  1273. IoQueuedRecursive: copyBlkioEntry(stats.Blkio.IoQueuedRecursive),
  1274. IoServiceTimeRecursive: copyBlkioEntry(stats.Blkio.IoServiceTimeRecursive),
  1275. IoWaitTimeRecursive: copyBlkioEntry(stats.Blkio.IoWaitTimeRecursive),
  1276. IoMergedRecursive: copyBlkioEntry(stats.Blkio.IoMergedRecursive),
  1277. IoTimeRecursive: copyBlkioEntry(stats.Blkio.IoTimeRecursive),
  1278. SectorsRecursive: copyBlkioEntry(stats.Blkio.SectorsRecursive),
  1279. }
  1280. }
  1281. if stats.CPU != nil {
  1282. s.CPUStats = types.CPUStats{
  1283. CPUUsage: types.CPUUsage{
  1284. TotalUsage: stats.CPU.Usage.Total,
  1285. PercpuUsage: stats.CPU.Usage.PerCPU,
  1286. UsageInKernelmode: stats.CPU.Usage.Kernel,
  1287. UsageInUsermode: stats.CPU.Usage.User,
  1288. },
  1289. ThrottlingData: types.ThrottlingData{
  1290. Periods: stats.CPU.Throttling.Periods,
  1291. ThrottledPeriods: stats.CPU.Throttling.ThrottledPeriods,
  1292. ThrottledTime: stats.CPU.Throttling.ThrottledTime,
  1293. },
  1294. }
  1295. }
  1296. if stats.Memory != nil {
  1297. raw := map[string]uint64{
  1298. "cache": stats.Memory.Cache,
  1299. "rss": stats.Memory.RSS,
  1300. "rss_huge": stats.Memory.RSSHuge,
  1301. "mapped_file": stats.Memory.MappedFile,
  1302. "dirty": stats.Memory.Dirty,
  1303. "writeback": stats.Memory.Writeback,
  1304. "pgpgin": stats.Memory.PgPgIn,
  1305. "pgpgout": stats.Memory.PgPgOut,
  1306. "pgfault": stats.Memory.PgFault,
  1307. "pgmajfault": stats.Memory.PgMajFault,
  1308. "inactive_anon": stats.Memory.InactiveAnon,
  1309. "active_anon": stats.Memory.ActiveAnon,
  1310. "inactive_file": stats.Memory.InactiveFile,
  1311. "active_file": stats.Memory.ActiveFile,
  1312. "unevictable": stats.Memory.Unevictable,
  1313. "hierarchical_memory_limit": stats.Memory.HierarchicalMemoryLimit,
  1314. "hierarchical_memsw_limit": stats.Memory.HierarchicalSwapLimit,
  1315. "total_cache": stats.Memory.TotalCache,
  1316. "total_rss": stats.Memory.TotalRSS,
  1317. "total_rss_huge": stats.Memory.TotalRSSHuge,
  1318. "total_mapped_file": stats.Memory.TotalMappedFile,
  1319. "total_dirty": stats.Memory.TotalDirty,
  1320. "total_writeback": stats.Memory.TotalWriteback,
  1321. "total_pgpgin": stats.Memory.TotalPgPgIn,
  1322. "total_pgpgout": stats.Memory.TotalPgPgOut,
  1323. "total_pgfault": stats.Memory.TotalPgFault,
  1324. "total_pgmajfault": stats.Memory.TotalPgMajFault,
  1325. "total_inactive_anon": stats.Memory.TotalInactiveAnon,
  1326. "total_active_anon": stats.Memory.TotalActiveAnon,
  1327. "total_inactive_file": stats.Memory.TotalInactiveFile,
  1328. "total_active_file": stats.Memory.TotalActiveFile,
  1329. "total_unevictable": stats.Memory.TotalUnevictable,
  1330. }
  1331. if stats.Memory.Usage != nil {
  1332. s.MemoryStats = types.MemoryStats{
  1333. Stats: raw,
  1334. Usage: stats.Memory.Usage.Usage,
  1335. MaxUsage: stats.Memory.Usage.Max,
  1336. Limit: stats.Memory.Usage.Limit,
  1337. Failcnt: stats.Memory.Usage.Failcnt,
  1338. }
  1339. } else {
  1340. s.MemoryStats = types.MemoryStats{
  1341. Stats: raw,
  1342. }
  1343. }
  1344. // if the container does not set memory limit, use the machineMemory
  1345. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1346. s.MemoryStats.Limit = daemon.machineMemory
  1347. }
  1348. }
  1349. if stats.Pids != nil {
  1350. s.PidsStats = types.PidsStats{
  1351. Current: stats.Pids.Current,
  1352. Limit: stats.Pids.Limit,
  1353. }
  1354. }
  1355. return s, nil
  1356. }
  1357. func (daemon *Daemon) statsV2(s *types.StatsJSON, stats *statsV2.Metrics) (*types.StatsJSON, error) {
  1358. if stats.Io != nil {
  1359. var isbr []types.BlkioStatEntry
  1360. for _, re := range stats.Io.Usage {
  1361. isbr = append(isbr,
  1362. types.BlkioStatEntry{
  1363. Major: re.Major,
  1364. Minor: re.Minor,
  1365. Op: "read",
  1366. Value: re.Rbytes,
  1367. },
  1368. types.BlkioStatEntry{
  1369. Major: re.Major,
  1370. Minor: re.Minor,
  1371. Op: "write",
  1372. Value: re.Wbytes,
  1373. },
  1374. )
  1375. }
  1376. s.BlkioStats = types.BlkioStats{
  1377. IoServiceBytesRecursive: isbr,
  1378. // Other fields are unsupported
  1379. }
  1380. }
  1381. if stats.CPU != nil {
  1382. s.CPUStats = types.CPUStats{
  1383. CPUUsage: types.CPUUsage{
  1384. TotalUsage: stats.CPU.UsageUsec * 1000,
  1385. // PercpuUsage is not supported
  1386. UsageInKernelmode: stats.CPU.SystemUsec * 1000,
  1387. UsageInUsermode: stats.CPU.UserUsec * 1000,
  1388. },
  1389. ThrottlingData: types.ThrottlingData{
  1390. Periods: stats.CPU.NrPeriods,
  1391. ThrottledPeriods: stats.CPU.NrThrottled,
  1392. ThrottledTime: stats.CPU.ThrottledUsec * 1000,
  1393. },
  1394. }
  1395. }
  1396. if stats.Memory != nil {
  1397. s.MemoryStats = types.MemoryStats{
  1398. // Stats is not compatible with v1
  1399. Stats: map[string]uint64{
  1400. "anon": stats.Memory.Anon,
  1401. "file": stats.Memory.File,
  1402. "kernel_stack": stats.Memory.KernelStack,
  1403. "slab": stats.Memory.Slab,
  1404. "sock": stats.Memory.Sock,
  1405. "shmem": stats.Memory.Shmem,
  1406. "file_mapped": stats.Memory.FileMapped,
  1407. "file_dirty": stats.Memory.FileDirty,
  1408. "file_writeback": stats.Memory.FileWriteback,
  1409. "anon_thp": stats.Memory.AnonThp,
  1410. "inactive_anon": stats.Memory.InactiveAnon,
  1411. "active_anon": stats.Memory.ActiveAnon,
  1412. "inactive_file": stats.Memory.InactiveFile,
  1413. "active_file": stats.Memory.ActiveFile,
  1414. "unevictable": stats.Memory.Unevictable,
  1415. "slab_reclaimable": stats.Memory.SlabReclaimable,
  1416. "slab_unreclaimable": stats.Memory.SlabUnreclaimable,
  1417. "pgfault": stats.Memory.Pgfault,
  1418. "pgmajfault": stats.Memory.Pgmajfault,
  1419. "workingset_refault": stats.Memory.WorkingsetRefault,
  1420. "workingset_activate": stats.Memory.WorkingsetActivate,
  1421. "workingset_nodereclaim": stats.Memory.WorkingsetNodereclaim,
  1422. "pgrefill": stats.Memory.Pgrefill,
  1423. "pgscan": stats.Memory.Pgscan,
  1424. "pgsteal": stats.Memory.Pgsteal,
  1425. "pgactivate": stats.Memory.Pgactivate,
  1426. "pgdeactivate": stats.Memory.Pgdeactivate,
  1427. "pglazyfree": stats.Memory.Pglazyfree,
  1428. "pglazyfreed": stats.Memory.Pglazyfreed,
  1429. "thp_fault_alloc": stats.Memory.ThpFaultAlloc,
  1430. "thp_collapse_alloc": stats.Memory.ThpCollapseAlloc,
  1431. },
  1432. Usage: stats.Memory.Usage,
  1433. // MaxUsage is not supported
  1434. Limit: stats.Memory.UsageLimit,
  1435. }
  1436. // if the container does not set memory limit, use the machineMemory
  1437. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1438. s.MemoryStats.Limit = daemon.machineMemory
  1439. }
  1440. if stats.MemoryEvents != nil {
  1441. // Failcnt is set to the "oom" field of the "memory.events" file.
  1442. // See https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
  1443. s.MemoryStats.Failcnt = stats.MemoryEvents.Oom
  1444. }
  1445. }
  1446. if stats.Pids != nil {
  1447. s.PidsStats = types.PidsStats{
  1448. Current: stats.Pids.Current,
  1449. Limit: stats.Pids.Limit,
  1450. }
  1451. }
  1452. return s, nil
  1453. }
  1454. // setDefaultIsolation determines the default isolation mode for the
  1455. // daemon to run in. This is only applicable on Windows
  1456. func (daemon *Daemon) setDefaultIsolation() error {
  1457. return nil
  1458. }
  1459. // setupDaemonProcess sets various settings for the daemon's process
  1460. func setupDaemonProcess(config *config.Config) error {
  1461. // setup the daemons oom_score_adj
  1462. if err := setupOOMScoreAdj(config.OOMScoreAdjust); err != nil {
  1463. return err
  1464. }
  1465. if err := setMayDetachMounts(); err != nil {
  1466. logrus.WithError(err).Warn("Could not set may_detach_mounts kernel parameter")
  1467. }
  1468. return nil
  1469. }
  1470. // This is used to allow removal of mountpoints that may be mounted in other
  1471. // namespaces on RHEL based kernels starting from RHEL 7.4.
  1472. // Without this setting, removals on these RHEL based kernels may fail with
  1473. // "device or resource busy".
  1474. // This setting is not available in upstream kernels as it is not configurable,
  1475. // but has been in the upstream kernels since 3.15.
  1476. func setMayDetachMounts() error {
  1477. f, err := os.OpenFile("/proc/sys/fs/may_detach_mounts", os.O_WRONLY, 0)
  1478. if err != nil {
  1479. if os.IsNotExist(err) {
  1480. return nil
  1481. }
  1482. return errors.Wrap(err, "error opening may_detach_mounts kernel config file")
  1483. }
  1484. defer f.Close()
  1485. _, err = f.WriteString("1")
  1486. if os.IsPermission(err) {
  1487. // Setting may_detach_mounts does not work in an
  1488. // unprivileged container. Ignore the error, but log
  1489. // it if we appear not to be in that situation.
  1490. if !userns.RunningInUserNS() {
  1491. logrus.Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
  1492. }
  1493. return nil
  1494. }
  1495. return err
  1496. }
  1497. func setupOOMScoreAdj(score int) error {
  1498. if score == 0 {
  1499. return nil
  1500. }
  1501. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1502. if err != nil {
  1503. return err
  1504. }
  1505. defer f.Close()
  1506. stringScore := strconv.Itoa(score)
  1507. _, err = f.WriteString(stringScore)
  1508. if os.IsPermission(err) {
  1509. // Setting oom_score_adj does not work in an
  1510. // unprivileged container. Ignore the error, but log
  1511. // it if we appear not to be in that situation.
  1512. if !userns.RunningInUserNS() {
  1513. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1514. }
  1515. return nil
  1516. }
  1517. return err
  1518. }
  1519. func (daemon *Daemon) initCPURtController(mnt, path string) error {
  1520. if path == "/" || path == "." {
  1521. return nil
  1522. }
  1523. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1524. // for the period and runtime as this limits what the children can be set to.
  1525. if err := daemon.initCPURtController(mnt, filepath.Dir(path)); err != nil {
  1526. return err
  1527. }
  1528. path = filepath.Join(mnt, path)
  1529. if err := os.MkdirAll(path, 0755); err != nil {
  1530. return err
  1531. }
  1532. if err := maybeCreateCPURealTimeFile(daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1533. return err
  1534. }
  1535. return maybeCreateCPURealTimeFile(daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path)
  1536. }
  1537. func maybeCreateCPURealTimeFile(configValue int64, file string, path string) error {
  1538. if configValue == 0 {
  1539. return nil
  1540. }
  1541. return os.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700)
  1542. }
  1543. func (daemon *Daemon) setupSeccompProfile() error {
  1544. switch profile := daemon.configStore.SeccompProfile; profile {
  1545. case "", config.SeccompProfileDefault:
  1546. daemon.seccompProfilePath = config.SeccompProfileDefault
  1547. case config.SeccompProfileUnconfined:
  1548. daemon.seccompProfilePath = config.SeccompProfileUnconfined
  1549. default:
  1550. daemon.seccompProfilePath = profile
  1551. b, err := os.ReadFile(profile)
  1552. if err != nil {
  1553. return fmt.Errorf("opening seccomp profile (%s) failed: %v", profile, err)
  1554. }
  1555. daemon.seccompProfile = b
  1556. }
  1557. return nil
  1558. }
  1559. // RawSysInfo returns *sysinfo.SysInfo .
  1560. func (daemon *Daemon) RawSysInfo() *sysinfo.SysInfo {
  1561. var siOpts []sysinfo.Opt
  1562. if daemon.getCgroupDriver() == cgroupSystemdDriver {
  1563. if euid := os.Getenv("ROOTLESSKIT_PARENT_EUID"); euid != "" {
  1564. siOpts = append(siOpts, sysinfo.WithCgroup2GroupPath("/user.slice/user-"+euid+".slice"))
  1565. }
  1566. }
  1567. return sysinfo.New(siOpts...)
  1568. }
  1569. func recursiveUnmount(target string) error {
  1570. return mount.RecursiveUnmount(target)
  1571. }
  1572. func (daemon *Daemon) initLibcontainerd(ctx context.Context) error {
  1573. var err error
  1574. daemon.containerd, err = remote.NewClient(
  1575. ctx,
  1576. daemon.containerdCli,
  1577. filepath.Join(daemon.configStore.ExecRoot, "containerd"),
  1578. daemon.configStore.ContainerdNamespace,
  1579. daemon,
  1580. )
  1581. return err
  1582. }