daemon_unix.go 63 KB

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