daemon_unix.go 63 KB

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