daemon_unix.go 62 KB

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