daemon_unix.go 63 KB

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