daemon_unix.go 64 KB

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