daemon_unix.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  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/netutils"
  36. "github.com/docker/docker/libnetwork/options"
  37. lntypes "github.com/docker/docker/libnetwork/types"
  38. "github.com/docker/docker/opts"
  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. // It's not kernel limit, we want this 6M limit to account for overhead during startup, and to supply a reasonable functional container
  60. linuxMinMemory = 6291456
  61. // constants for remapped root settings
  62. defaultIDSpecifier = "default"
  63. defaultRemappedID = "dockremap"
  64. // constant for cgroup drivers
  65. cgroupFsDriver = "cgroupfs"
  66. cgroupSystemdDriver = "systemd"
  67. cgroupNoneDriver = "none"
  68. )
  69. type containerGetter interface {
  70. GetContainer(string) (*container.Container, error)
  71. }
  72. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  73. memory := specs.LinuxMemory{}
  74. if config.Memory > 0 {
  75. memory.Limit = &config.Memory
  76. }
  77. if config.MemoryReservation > 0 {
  78. memory.Reservation = &config.MemoryReservation
  79. }
  80. if config.MemorySwap > 0 {
  81. memory.Swap = &config.MemorySwap
  82. }
  83. if config.MemorySwappiness != nil {
  84. swappiness := uint64(*config.MemorySwappiness)
  85. memory.Swappiness = &swappiness
  86. }
  87. if config.OomKillDisable != nil {
  88. memory.DisableOOMKiller = config.OomKillDisable
  89. }
  90. if config.KernelMemory != 0 {
  91. memory.Kernel = &config.KernelMemory
  92. }
  93. if config.KernelMemoryTCP != 0 {
  94. memory.KernelTCP = &config.KernelMemoryTCP
  95. }
  96. return &memory
  97. }
  98. func getPidsLimit(config containertypes.Resources) *specs.LinuxPids {
  99. if config.PidsLimit == nil {
  100. return nil
  101. }
  102. if *config.PidsLimit <= 0 {
  103. // docker API allows 0 and negative values to unset this to be consistent
  104. // with default values. When updating values, runc requires -1 to unset
  105. // the previous limit.
  106. return &specs.LinuxPids{Limit: -1}
  107. }
  108. return &specs.LinuxPids{Limit: *config.PidsLimit}
  109. }
  110. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  111. cpu := specs.LinuxCPU{}
  112. if config.CPUShares < 0 {
  113. return nil, fmt.Errorf("shares: invalid argument")
  114. }
  115. if config.CPUShares >= 0 {
  116. shares := uint64(config.CPUShares)
  117. cpu.Shares = &shares
  118. }
  119. if config.CpusetCpus != "" {
  120. cpu.Cpus = config.CpusetCpus
  121. }
  122. if config.CpusetMems != "" {
  123. cpu.Mems = config.CpusetMems
  124. }
  125. if config.NanoCPUs > 0 {
  126. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  127. period := uint64(100 * time.Millisecond / time.Microsecond)
  128. quota := config.NanoCPUs * int64(period) / 1e9
  129. cpu.Period = &period
  130. cpu.Quota = &quota
  131. }
  132. if config.CPUPeriod != 0 {
  133. period := uint64(config.CPUPeriod)
  134. cpu.Period = &period
  135. }
  136. if config.CPUQuota != 0 {
  137. q := config.CPUQuota
  138. cpu.Quota = &q
  139. }
  140. if config.CPURealtimePeriod != 0 {
  141. period := uint64(config.CPURealtimePeriod)
  142. cpu.RealtimePeriod = &period
  143. }
  144. if config.CPURealtimeRuntime != 0 {
  145. c := config.CPURealtimeRuntime
  146. cpu.RealtimeRuntime = &c
  147. }
  148. return &cpu, nil
  149. }
  150. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  151. var stat unix.Stat_t
  152. var blkioWeightDevices []specs.LinuxWeightDevice
  153. for _, weightDevice := range config.BlkioWeightDevice {
  154. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  155. return nil, errors.WithStack(&os.PathError{Op: "stat", Path: weightDevice.Path, Err: err})
  156. }
  157. weight := weightDevice.Weight
  158. d := specs.LinuxWeightDevice{Weight: &weight}
  159. // The type is 32bit on mips.
  160. d.Major = int64(unix.Major(uint64(stat.Rdev))) //nolint: unconvert
  161. d.Minor = int64(unix.Minor(uint64(stat.Rdev))) //nolint: unconvert
  162. blkioWeightDevices = append(blkioWeightDevices, d)
  163. }
  164. return blkioWeightDevices, nil
  165. }
  166. func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfig *containertypes.HostConfig) error {
  167. container.NoNewPrivileges = daemon.configStore.NoNewPrivileges
  168. return parseSecurityOpt(container, hostConfig)
  169. }
  170. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  171. var (
  172. labelOpts []string
  173. err error
  174. )
  175. for _, opt := range config.SecurityOpt {
  176. if opt == "no-new-privileges" {
  177. container.NoNewPrivileges = true
  178. continue
  179. }
  180. if opt == "disable" {
  181. labelOpts = append(labelOpts, "disable")
  182. continue
  183. }
  184. var k, v string
  185. var ok bool
  186. if strings.Contains(opt, "=") {
  187. k, v, ok = strings.Cut(opt, "=")
  188. } else if strings.Contains(opt, ":") {
  189. k, v, ok = strings.Cut(opt, ":")
  190. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  191. }
  192. if !ok {
  193. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  194. }
  195. switch k {
  196. case "label":
  197. labelOpts = append(labelOpts, v)
  198. case "apparmor":
  199. container.AppArmorProfile = v
  200. case "seccomp":
  201. container.SeccompProfile = v
  202. case "no-new-privileges":
  203. noNewPrivileges, err := strconv.ParseBool(v)
  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 _, err := daemon.getRuntime(hostConfig.Runtime); err != nil {
  637. return warnings, err
  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. return warnings, nil
  654. }
  655. // verifyDaemonSettings performs validation of daemon config struct
  656. func verifyDaemonSettings(conf *config.Config) error {
  657. if conf.ContainerdNamespace == conf.ContainerdPluginNamespace {
  658. return errors.New("containers namespace and plugins namespace cannot be the same")
  659. }
  660. // Check for mutually incompatible config options
  661. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  662. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  663. }
  664. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  665. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  666. }
  667. if conf.BridgeConfig.EnableIP6Tables && !conf.Experimental {
  668. return fmt.Errorf("ip6tables rules are only available if experimental features are enabled")
  669. }
  670. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  671. conf.BridgeConfig.EnableIPMasq = false
  672. }
  673. if err := verifyCgroupDriver(conf); err != nil {
  674. return err
  675. }
  676. if conf.CgroupParent != "" && UsingSystemd(conf) {
  677. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  678. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  679. }
  680. }
  681. if conf.Rootless && UsingSystemd(conf) && cgroups.Mode() != cgroups.Unified {
  682. return fmt.Errorf("exec-opt native.cgroupdriver=systemd requires cgroup v2 for rootless mode")
  683. }
  684. configureRuntimes(conf)
  685. if rtName := conf.GetDefaultRuntimeName(); rtName != "" {
  686. if conf.GetRuntime(rtName) == nil {
  687. if !config.IsPermissibleC8dRuntimeName(rtName) {
  688. return fmt.Errorf("specified default runtime '%s' does not exist", rtName)
  689. }
  690. }
  691. }
  692. return nil
  693. }
  694. // checkSystem validates platform-specific requirements
  695. func checkSystem() error {
  696. return nil
  697. }
  698. // configureMaxThreads sets the Go runtime max threads threshold
  699. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  700. func configureMaxThreads(config *config.Config) error {
  701. mt, err := os.ReadFile("/proc/sys/kernel/threads-max")
  702. if err != nil {
  703. return err
  704. }
  705. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  706. if err != nil {
  707. return err
  708. }
  709. maxThreads := (mtint / 100) * 90
  710. debug.SetMaxThreads(maxThreads)
  711. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  712. return nil
  713. }
  714. func overlaySupportsSelinux() (bool, error) {
  715. f, err := os.Open("/proc/kallsyms")
  716. if err != nil {
  717. if os.IsNotExist(err) {
  718. return false, nil
  719. }
  720. return false, err
  721. }
  722. defer f.Close()
  723. s := bufio.NewScanner(f)
  724. for s.Scan() {
  725. if strings.HasSuffix(s.Text(), " security_inode_copy_up") {
  726. return true, nil
  727. }
  728. }
  729. return false, s.Err()
  730. }
  731. // configureKernelSecuritySupport configures and validates security support for the kernel
  732. func configureKernelSecuritySupport(config *config.Config, driverName string) error {
  733. if config.EnableSelinuxSupport {
  734. if !selinux.GetEnabled() {
  735. logrus.Warn("Docker could not enable SELinux on the host system")
  736. return nil
  737. }
  738. if driverName == "overlay" || driverName == "overlay2" || driverName == "overlayfs" {
  739. // If driver is overlay or overlay2, make sure kernel
  740. // supports selinux with overlay.
  741. supported, err := overlaySupportsSelinux()
  742. if err != nil {
  743. return err
  744. }
  745. if !supported {
  746. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverName)
  747. }
  748. }
  749. } else {
  750. selinux.SetDisabled()
  751. }
  752. return nil
  753. }
  754. // initNetworkController initializes the libnetwork controller and configures
  755. // network settings. If there's active sandboxes, configuration changes will not
  756. // take effect.
  757. func (daemon *Daemon) initNetworkController(activeSandboxes map[string]interface{}) error {
  758. netOptions, err := daemon.networkOptions(daemon.PluginStore, activeSandboxes)
  759. if err != nil {
  760. return err
  761. }
  762. daemon.netController, err = libnetwork.New(netOptions...)
  763. if err != nil {
  764. return fmt.Errorf("error obtaining controller instance: %v", err)
  765. }
  766. if len(activeSandboxes) > 0 {
  767. logrus.Info("there are running containers, updated network configuration will not take affect")
  768. } else if err := configureNetworking(daemon.netController, daemon.configStore); err != nil {
  769. return err
  770. }
  771. // Set HostGatewayIP to the default bridge's IP if it is empty
  772. setHostGatewayIP(daemon.netController, daemon.configStore)
  773. return nil
  774. }
  775. func configureNetworking(controller libnetwork.NetworkController, conf *config.Config) error {
  776. // Initialize default network on "null"
  777. if n, _ := controller.NetworkByName("none"); n == nil {
  778. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  779. return errors.Wrap(err, `error creating default "null" network`)
  780. }
  781. }
  782. // Initialize default network on "host"
  783. if n, _ := controller.NetworkByName("host"); n == nil {
  784. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  785. return errors.Wrap(err, `error creating default "host" network`)
  786. }
  787. }
  788. // Clear stale bridge network
  789. if n, err := controller.NetworkByName("bridge"); err == nil {
  790. if err = n.Delete(); err != nil {
  791. return errors.Wrap(err, `could not delete the default "bridge"" network`)
  792. }
  793. if len(conf.NetworkConfig.DefaultAddressPools.Value()) > 0 && !conf.LiveRestoreEnabled {
  794. removeDefaultBridgeInterface()
  795. }
  796. }
  797. if !conf.DisableBridge {
  798. // Initialize default driver "bridge"
  799. if err := initBridgeDriver(controller, conf); err != nil {
  800. return err
  801. }
  802. } else {
  803. removeDefaultBridgeInterface()
  804. }
  805. return nil
  806. }
  807. // setHostGatewayIP sets cfg.HostGatewayIP to the default bridge's IP if it is empty.
  808. func setHostGatewayIP(controller libnetwork.NetworkController, config *config.Config) {
  809. if config.HostGatewayIP != nil {
  810. return
  811. }
  812. if n, err := controller.NetworkByName("bridge"); err == nil {
  813. v4Info, v6Info := n.Info().IpamInfo()
  814. var gateway net.IP
  815. if len(v4Info) > 0 {
  816. gateway = v4Info[0].Gateway.IP
  817. } else if len(v6Info) > 0 {
  818. gateway = v6Info[0].Gateway.IP
  819. }
  820. config.HostGatewayIP = gateway
  821. }
  822. }
  823. func driverOptions(config *config.Config) nwconfig.Option {
  824. return nwconfig.OptionDriverConfig("bridge", options.Generic{
  825. netlabel.GenericData: options.Generic{
  826. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  827. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  828. "EnableIP6Tables": config.BridgeConfig.EnableIP6Tables,
  829. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  830. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath,
  831. },
  832. })
  833. }
  834. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  835. bridgeName := bridge.DefaultBridgeName
  836. if config.BridgeConfig.Iface != "" {
  837. bridgeName = config.BridgeConfig.Iface
  838. }
  839. netOption := map[string]string{
  840. bridge.BridgeName: bridgeName,
  841. bridge.DefaultBridge: strconv.FormatBool(true),
  842. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  843. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  844. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  845. }
  846. // --ip processing
  847. if config.BridgeConfig.DefaultIP != nil {
  848. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  849. }
  850. ipamV4Conf := &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  851. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  852. if err != nil {
  853. return errors.Wrap(err, "list bridge addresses failed")
  854. }
  855. nw := nwList[0]
  856. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  857. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  858. if err != nil {
  859. return errors.Wrap(err, "parse CIDR failed")
  860. }
  861. // Iterate through in case there are multiple addresses for the bridge
  862. for _, entry := range nwList {
  863. if fCIDR.Contains(entry.IP) {
  864. nw = entry
  865. break
  866. }
  867. }
  868. }
  869. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  870. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  871. if hip.IsGlobalUnicast() {
  872. ipamV4Conf.Gateway = nw.IP.String()
  873. }
  874. if config.BridgeConfig.IP != "" {
  875. ip, ipNet, err := net.ParseCIDR(config.BridgeConfig.IP)
  876. if err != nil {
  877. return err
  878. }
  879. ipamV4Conf.PreferredPool = ipNet.String()
  880. ipamV4Conf.Gateway = ip.String()
  881. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  882. 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)
  883. }
  884. if config.BridgeConfig.FixedCIDR != "" {
  885. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  886. if err != nil {
  887. return err
  888. }
  889. ipamV4Conf.SubPool = fCIDR.String()
  890. }
  891. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  892. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  893. }
  894. var (
  895. deferIPv6Alloc bool
  896. ipamV6Conf *libnetwork.IpamConf
  897. )
  898. if config.BridgeConfig.EnableIPv6 && config.BridgeConfig.FixedCIDRv6 == "" {
  899. 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"))
  900. } else if config.BridgeConfig.FixedCIDRv6 != "" {
  901. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  902. if err != nil {
  903. return err
  904. }
  905. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  906. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  907. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  908. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  909. // on this network until after the driver has created the endpoint and returned the
  910. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  911. ones, _ := fCIDRv6.Mask.Size()
  912. deferIPv6Alloc = ones <= 80
  913. ipamV6Conf = &libnetwork.IpamConf{
  914. AuxAddresses: make(map[string]string),
  915. PreferredPool: fCIDRv6.String(),
  916. }
  917. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  918. // address belongs to the same network, we need to inform libnetwork about it, so
  919. // that it can be reserved with IPAM and it will not be given away to somebody else
  920. for _, nw6 := range nw6List {
  921. if fCIDRv6.Contains(nw6.IP) {
  922. ipamV6Conf.Gateway = nw6.IP.String()
  923. break
  924. }
  925. }
  926. }
  927. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  928. if ipamV6Conf == nil {
  929. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  930. }
  931. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  932. }
  933. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  934. v6Conf := []*libnetwork.IpamConf{}
  935. if ipamV6Conf != nil {
  936. v6Conf = append(v6Conf, ipamV6Conf)
  937. }
  938. // Initialize default network on "bridge" with the same name
  939. _, err = controller.NewNetwork("bridge", "bridge", "",
  940. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  941. libnetwork.NetworkOptionDriverOpts(netOption),
  942. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  943. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  944. if err != nil {
  945. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  946. }
  947. return nil
  948. }
  949. // Remove default bridge interface if present (--bridge=none use case)
  950. func removeDefaultBridgeInterface() {
  951. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  952. if err := netlink.LinkDel(lnk); err != nil {
  953. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  954. }
  955. }
  956. }
  957. func setupInitLayer(idMapping idtools.IdentityMapping) func(string) error {
  958. return func(initPath string) error {
  959. return initlayer.Setup(initPath, idMapping.RootPair())
  960. }
  961. }
  962. // Parse the remapped root (user namespace) option, which can be one of:
  963. //
  964. // - username - valid username from /etc/passwd
  965. // - username:groupname - valid username; valid groupname from /etc/group
  966. // - uid - 32-bit unsigned int valid Linux UID value
  967. // - uid:gid - uid value; 32-bit unsigned int Linux GID value
  968. //
  969. // If no groupname is specified, and a username is specified, an attempt
  970. // will be made to lookup a gid for that username as a groupname
  971. //
  972. // If names are used, they are verified to exist in passwd/group
  973. func parseRemappedRoot(usergrp string) (string, string, error) {
  974. var (
  975. userID, groupID int
  976. username, groupname string
  977. )
  978. idparts := strings.Split(usergrp, ":")
  979. if len(idparts) > 2 {
  980. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  981. }
  982. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  983. // must be a uid; take it as valid
  984. userID = int(uid)
  985. luser, err := idtools.LookupUID(userID)
  986. if err != nil {
  987. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  988. }
  989. username = luser.Name
  990. if len(idparts) == 1 {
  991. // if the uid was numeric and no gid was specified, take the uid as the gid
  992. groupID = userID
  993. lgrp, err := idtools.LookupGID(groupID)
  994. if err != nil {
  995. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  996. }
  997. groupname = lgrp.Name
  998. }
  999. } else {
  1000. lookupName := idparts[0]
  1001. // special case: if the user specified "default", they want Docker to create or
  1002. // use (after creation) the "dockremap" user/group for root remapping
  1003. if lookupName == defaultIDSpecifier {
  1004. lookupName = defaultRemappedID
  1005. }
  1006. luser, err := idtools.LookupUser(lookupName)
  1007. if err != nil && idparts[0] != defaultIDSpecifier {
  1008. // error if the name requested isn't the special "dockremap" ID
  1009. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  1010. } else if err != nil {
  1011. // special case-- if the username == "default", then we have been asked
  1012. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  1013. // ranges will be used for the user and group mappings in user namespaced containers
  1014. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  1015. if err == nil {
  1016. return defaultRemappedID, defaultRemappedID, nil
  1017. }
  1018. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  1019. }
  1020. username = luser.Name
  1021. if len(idparts) == 1 {
  1022. // we only have a string username, and no group specified; look up gid from username as group
  1023. group, err := idtools.LookupGroup(lookupName)
  1024. if err != nil {
  1025. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  1026. }
  1027. groupname = group.Name
  1028. }
  1029. }
  1030. if len(idparts) == 2 {
  1031. // groupname or gid is separately specified and must be resolved
  1032. // to an unsigned 32-bit gid
  1033. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  1034. // must be a gid, take it as valid
  1035. groupID = int(gid)
  1036. lgrp, err := idtools.LookupGID(groupID)
  1037. if err != nil {
  1038. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  1039. }
  1040. groupname = lgrp.Name
  1041. } else {
  1042. // not a number; attempt a lookup
  1043. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  1044. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  1045. }
  1046. groupname = idparts[1]
  1047. }
  1048. }
  1049. return username, groupname, nil
  1050. }
  1051. func setupRemappedRoot(config *config.Config) (idtools.IdentityMapping, error) {
  1052. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  1053. return idtools.IdentityMapping{}, fmt.Errorf("User namespaces are only supported on Linux")
  1054. }
  1055. // if the daemon was started with remapped root option, parse
  1056. // the config option to the int uid,gid values
  1057. if config.RemappedRoot != "" {
  1058. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  1059. if err != nil {
  1060. return idtools.IdentityMapping{}, err
  1061. }
  1062. if username == "root" {
  1063. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  1064. // effectively
  1065. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  1066. return idtools.IdentityMapping{}, nil
  1067. }
  1068. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s", username)
  1069. // update remapped root setting now that we have resolved them to actual names
  1070. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  1071. mappings, err := idtools.LoadIdentityMapping(username)
  1072. if err != nil {
  1073. return idtools.IdentityMapping{}, errors.Wrap(err, "Can't create ID mappings")
  1074. }
  1075. return mappings, nil
  1076. }
  1077. return idtools.IdentityMapping{}, nil
  1078. }
  1079. func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools.Identity) error {
  1080. config.Root = rootDir
  1081. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  1082. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  1083. // (e.g. mounted layers of a container) can traverse this path.
  1084. // The user namespace support will create subdirectories for the remapped root host uid:gid
  1085. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  1086. // layer content subtrees.
  1087. if _, err := os.Stat(rootDir); err == nil {
  1088. // root current exists; verify the access bits are correct by setting them
  1089. if err = os.Chmod(rootDir, 0711); err != nil {
  1090. return err
  1091. }
  1092. } else if os.IsNotExist(err) {
  1093. // no root exists yet, create it 0711 with root:root ownership
  1094. if err := os.MkdirAll(rootDir, 0711); err != nil {
  1095. return err
  1096. }
  1097. }
  1098. id := idtools.Identity{UID: idtools.CurrentIdentity().UID, GID: remappedRoot.GID}
  1099. // First make sure the current root dir has the correct perms.
  1100. if err := idtools.MkdirAllAndChown(config.Root, 0710, id); err != nil {
  1101. return errors.Wrapf(err, "could not create or set daemon root permissions: %s", config.Root)
  1102. }
  1103. // if user namespaces are enabled we will create a subtree underneath the specified root
  1104. // with any/all specified remapped root uid/gid options on the daemon creating
  1105. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  1106. // `chdir()` to work for containers namespaced to that uid/gid)
  1107. if config.RemappedRoot != "" {
  1108. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", remappedRoot.UID, remappedRoot.GID))
  1109. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  1110. // Create the root directory if it doesn't exist
  1111. if err := idtools.MkdirAllAndChown(config.Root, 0710, id); err != nil {
  1112. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  1113. }
  1114. // we also need to verify that any pre-existing directories in the path to
  1115. // the graphroot won't block access to remapped root--if any pre-existing directory
  1116. // has strict permissions that don't allow "x", container start will fail, so
  1117. // better to warn and fail now
  1118. dirPath := config.Root
  1119. for {
  1120. dirPath = filepath.Dir(dirPath)
  1121. if dirPath == "/" {
  1122. break
  1123. }
  1124. if !canAccess(dirPath, remappedRoot) {
  1125. return fmt.Errorf("a subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories", config.Root)
  1126. }
  1127. }
  1128. }
  1129. if err := setupDaemonRootPropagation(config); err != nil {
  1130. logrus.WithError(err).WithField("dir", config.Root).Warn("Error while setting daemon root propagation, this is not generally critical but may cause some functionality to not work or fallback to less desirable behavior")
  1131. }
  1132. return nil
  1133. }
  1134. // canAccess takes a valid (existing) directory and a uid, gid pair and determines
  1135. // if that uid, gid pair has access (execute bit) to the directory.
  1136. //
  1137. // Note: this is a very rudimentary check, and may not produce accurate results,
  1138. // so should not be used for anything other than the current use, see:
  1139. // https://github.com/moby/moby/issues/43724
  1140. func canAccess(path string, pair idtools.Identity) bool {
  1141. statInfo, err := os.Stat(path)
  1142. if err != nil {
  1143. return false
  1144. }
  1145. perms := statInfo.Mode().Perm()
  1146. if perms&0o001 == 0o001 {
  1147. // world access
  1148. return true
  1149. }
  1150. ssi := statInfo.Sys().(*syscall.Stat_t)
  1151. if ssi.Uid == uint32(pair.UID) && (perms&0o100 == 0o100) {
  1152. // owner access.
  1153. return true
  1154. }
  1155. if ssi.Gid == uint32(pair.GID) && (perms&0o010 == 0o010) {
  1156. // group access.
  1157. return true
  1158. }
  1159. return false
  1160. }
  1161. func setupDaemonRootPropagation(cfg *config.Config) error {
  1162. rootParentMount, mountOptions, err := getSourceMount(cfg.Root)
  1163. if err != nil {
  1164. return errors.Wrap(err, "error getting daemon root's parent mount")
  1165. }
  1166. var cleanupOldFile bool
  1167. cleanupFile := getUnmountOnShutdownPath(cfg)
  1168. defer func() {
  1169. if !cleanupOldFile {
  1170. return
  1171. }
  1172. if err := os.Remove(cleanupFile); err != nil && !os.IsNotExist(err) {
  1173. logrus.WithError(err).WithField("file", cleanupFile).Warn("could not clean up old root propagation unmount file")
  1174. }
  1175. }()
  1176. if hasMountInfoOption(mountOptions, sharedPropagationOption, slavePropagationOption) {
  1177. cleanupOldFile = true
  1178. return nil
  1179. }
  1180. if err := mount.MakeShared(cfg.Root); err != nil {
  1181. return errors.Wrap(err, "could not setup daemon root propagation to shared")
  1182. }
  1183. // check the case where this may have already been a mount to itself.
  1184. // If so then the daemon only performed a remount and should not try to unmount this later.
  1185. if rootParentMount == cfg.Root {
  1186. cleanupOldFile = true
  1187. return nil
  1188. }
  1189. if err := os.MkdirAll(filepath.Dir(cleanupFile), 0700); err != nil {
  1190. return errors.Wrap(err, "error creating dir to store mount cleanup file")
  1191. }
  1192. if err := os.WriteFile(cleanupFile, nil, 0600); err != nil {
  1193. return errors.Wrap(err, "error writing file to signal mount cleanup on shutdown")
  1194. }
  1195. return nil
  1196. }
  1197. // getUnmountOnShutdownPath generates the path to used when writing the file that signals to the daemon that on shutdown
  1198. // the daemon root should be unmounted.
  1199. func getUnmountOnShutdownPath(config *config.Config) string {
  1200. return filepath.Join(config.ExecRoot, "unmount-on-shutdown")
  1201. }
  1202. // registerLinks registers network links between container and other containers
  1203. // with the daemon using the specification in hostConfig.
  1204. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1205. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1206. return nil
  1207. }
  1208. for _, l := range hostConfig.Links {
  1209. name, alias, err := opts.ParseLink(l)
  1210. if err != nil {
  1211. return err
  1212. }
  1213. child, err := daemon.GetContainer(name)
  1214. if err != nil {
  1215. if errdefs.IsNotFound(err) {
  1216. // Trying to link to a non-existing container is not valid, and
  1217. // should return an "invalid parameter" error. Returning a "not
  1218. // found" error here would make the client report the container's
  1219. // image could not be found (see moby/moby#39823)
  1220. err = errdefs.InvalidParameter(err)
  1221. }
  1222. return errors.Wrapf(err, "could not get container for %s", name)
  1223. }
  1224. for child.HostConfig.NetworkMode.IsContainer() {
  1225. cid := child.HostConfig.NetworkMode.ConnectedContainer()
  1226. child, err = daemon.GetContainer(cid)
  1227. if err != nil {
  1228. if errdefs.IsNotFound(err) {
  1229. // Trying to link to a non-existing container is not valid, and
  1230. // should return an "invalid parameter" error. Returning a "not
  1231. // found" error here would make the client report the container's
  1232. // image could not be found (see moby/moby#39823)
  1233. err = errdefs.InvalidParameter(err)
  1234. }
  1235. return errors.Wrapf(err, "could not get container for %s", cid)
  1236. }
  1237. }
  1238. if child.HostConfig.NetworkMode.IsHost() {
  1239. return runconfig.ErrConflictHostNetworkAndLinks
  1240. }
  1241. if err := daemon.registerLink(container, child, alias); err != nil {
  1242. return err
  1243. }
  1244. }
  1245. return nil
  1246. }
  1247. // conditionalMountOnStart is a platform specific helper function during the
  1248. // container start to call mount.
  1249. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1250. return daemon.Mount(container)
  1251. }
  1252. // conditionalUnmountOnCleanup is a platform specific helper function called
  1253. // during the cleanup of a container to unmount.
  1254. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1255. return daemon.Unmount(container)
  1256. }
  1257. func copyBlkioEntry(entries []*statsV1.BlkIOEntry) []types.BlkioStatEntry {
  1258. out := make([]types.BlkioStatEntry, len(entries))
  1259. for i, re := range entries {
  1260. out[i] = types.BlkioStatEntry{
  1261. Major: re.Major,
  1262. Minor: re.Minor,
  1263. Op: re.Op,
  1264. Value: re.Value,
  1265. }
  1266. }
  1267. return out
  1268. }
  1269. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1270. c.Lock()
  1271. task, err := c.GetRunningTask()
  1272. c.Unlock()
  1273. if err != nil {
  1274. return nil, err
  1275. }
  1276. cs, err := task.Stats(context.Background())
  1277. if err != nil {
  1278. if strings.Contains(err.Error(), "container not found") {
  1279. return nil, containerNotFound(c.ID)
  1280. }
  1281. return nil, err
  1282. }
  1283. s := &types.StatsJSON{}
  1284. s.Read = cs.Read
  1285. stats := cs.Metrics
  1286. switch t := stats.(type) {
  1287. case *statsV1.Metrics:
  1288. return daemon.statsV1(s, t)
  1289. case *statsV2.Metrics:
  1290. return daemon.statsV2(s, t)
  1291. default:
  1292. return nil, errors.Errorf("unexpected type of metrics %+v", t)
  1293. }
  1294. }
  1295. func (daemon *Daemon) statsV1(s *types.StatsJSON, stats *statsV1.Metrics) (*types.StatsJSON, error) {
  1296. if stats.Blkio != nil {
  1297. s.BlkioStats = types.BlkioStats{
  1298. IoServiceBytesRecursive: copyBlkioEntry(stats.Blkio.IoServiceBytesRecursive),
  1299. IoServicedRecursive: copyBlkioEntry(stats.Blkio.IoServicedRecursive),
  1300. IoQueuedRecursive: copyBlkioEntry(stats.Blkio.IoQueuedRecursive),
  1301. IoServiceTimeRecursive: copyBlkioEntry(stats.Blkio.IoServiceTimeRecursive),
  1302. IoWaitTimeRecursive: copyBlkioEntry(stats.Blkio.IoWaitTimeRecursive),
  1303. IoMergedRecursive: copyBlkioEntry(stats.Blkio.IoMergedRecursive),
  1304. IoTimeRecursive: copyBlkioEntry(stats.Blkio.IoTimeRecursive),
  1305. SectorsRecursive: copyBlkioEntry(stats.Blkio.SectorsRecursive),
  1306. }
  1307. }
  1308. if stats.CPU != nil {
  1309. s.CPUStats = types.CPUStats{
  1310. CPUUsage: types.CPUUsage{
  1311. TotalUsage: stats.CPU.Usage.Total,
  1312. PercpuUsage: stats.CPU.Usage.PerCPU,
  1313. UsageInKernelmode: stats.CPU.Usage.Kernel,
  1314. UsageInUsermode: stats.CPU.Usage.User,
  1315. },
  1316. ThrottlingData: types.ThrottlingData{
  1317. Periods: stats.CPU.Throttling.Periods,
  1318. ThrottledPeriods: stats.CPU.Throttling.ThrottledPeriods,
  1319. ThrottledTime: stats.CPU.Throttling.ThrottledTime,
  1320. },
  1321. }
  1322. }
  1323. if stats.Memory != nil {
  1324. raw := map[string]uint64{
  1325. "cache": stats.Memory.Cache,
  1326. "rss": stats.Memory.RSS,
  1327. "rss_huge": stats.Memory.RSSHuge,
  1328. "mapped_file": stats.Memory.MappedFile,
  1329. "dirty": stats.Memory.Dirty,
  1330. "writeback": stats.Memory.Writeback,
  1331. "pgpgin": stats.Memory.PgPgIn,
  1332. "pgpgout": stats.Memory.PgPgOut,
  1333. "pgfault": stats.Memory.PgFault,
  1334. "pgmajfault": stats.Memory.PgMajFault,
  1335. "inactive_anon": stats.Memory.InactiveAnon,
  1336. "active_anon": stats.Memory.ActiveAnon,
  1337. "inactive_file": stats.Memory.InactiveFile,
  1338. "active_file": stats.Memory.ActiveFile,
  1339. "unevictable": stats.Memory.Unevictable,
  1340. "hierarchical_memory_limit": stats.Memory.HierarchicalMemoryLimit,
  1341. "hierarchical_memsw_limit": stats.Memory.HierarchicalSwapLimit,
  1342. "total_cache": stats.Memory.TotalCache,
  1343. "total_rss": stats.Memory.TotalRSS,
  1344. "total_rss_huge": stats.Memory.TotalRSSHuge,
  1345. "total_mapped_file": stats.Memory.TotalMappedFile,
  1346. "total_dirty": stats.Memory.TotalDirty,
  1347. "total_writeback": stats.Memory.TotalWriteback,
  1348. "total_pgpgin": stats.Memory.TotalPgPgIn,
  1349. "total_pgpgout": stats.Memory.TotalPgPgOut,
  1350. "total_pgfault": stats.Memory.TotalPgFault,
  1351. "total_pgmajfault": stats.Memory.TotalPgMajFault,
  1352. "total_inactive_anon": stats.Memory.TotalInactiveAnon,
  1353. "total_active_anon": stats.Memory.TotalActiveAnon,
  1354. "total_inactive_file": stats.Memory.TotalInactiveFile,
  1355. "total_active_file": stats.Memory.TotalActiveFile,
  1356. "total_unevictable": stats.Memory.TotalUnevictable,
  1357. }
  1358. if stats.Memory.Usage != nil {
  1359. s.MemoryStats = types.MemoryStats{
  1360. Stats: raw,
  1361. Usage: stats.Memory.Usage.Usage,
  1362. MaxUsage: stats.Memory.Usage.Max,
  1363. Limit: stats.Memory.Usage.Limit,
  1364. Failcnt: stats.Memory.Usage.Failcnt,
  1365. }
  1366. } else {
  1367. s.MemoryStats = types.MemoryStats{
  1368. Stats: raw,
  1369. }
  1370. }
  1371. // if the container does not set memory limit, use the machineMemory
  1372. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1373. s.MemoryStats.Limit = daemon.machineMemory
  1374. }
  1375. }
  1376. if stats.Pids != nil {
  1377. s.PidsStats = types.PidsStats{
  1378. Current: stats.Pids.Current,
  1379. Limit: stats.Pids.Limit,
  1380. }
  1381. }
  1382. return s, nil
  1383. }
  1384. func (daemon *Daemon) statsV2(s *types.StatsJSON, stats *statsV2.Metrics) (*types.StatsJSON, error) {
  1385. if stats.Io != nil {
  1386. var isbr []types.BlkioStatEntry
  1387. for _, re := range stats.Io.Usage {
  1388. isbr = append(isbr,
  1389. types.BlkioStatEntry{
  1390. Major: re.Major,
  1391. Minor: re.Minor,
  1392. Op: "read",
  1393. Value: re.Rbytes,
  1394. },
  1395. types.BlkioStatEntry{
  1396. Major: re.Major,
  1397. Minor: re.Minor,
  1398. Op: "write",
  1399. Value: re.Wbytes,
  1400. },
  1401. )
  1402. }
  1403. s.BlkioStats = types.BlkioStats{
  1404. IoServiceBytesRecursive: isbr,
  1405. // Other fields are unsupported
  1406. }
  1407. }
  1408. if stats.CPU != nil {
  1409. s.CPUStats = types.CPUStats{
  1410. CPUUsage: types.CPUUsage{
  1411. TotalUsage: stats.CPU.UsageUsec * 1000,
  1412. // PercpuUsage is not supported
  1413. UsageInKernelmode: stats.CPU.SystemUsec * 1000,
  1414. UsageInUsermode: stats.CPU.UserUsec * 1000,
  1415. },
  1416. ThrottlingData: types.ThrottlingData{
  1417. Periods: stats.CPU.NrPeriods,
  1418. ThrottledPeriods: stats.CPU.NrThrottled,
  1419. ThrottledTime: stats.CPU.ThrottledUsec * 1000,
  1420. },
  1421. }
  1422. }
  1423. if stats.Memory != nil {
  1424. s.MemoryStats = types.MemoryStats{
  1425. // Stats is not compatible with v1
  1426. Stats: map[string]uint64{
  1427. "anon": stats.Memory.Anon,
  1428. "file": stats.Memory.File,
  1429. "kernel_stack": stats.Memory.KernelStack,
  1430. "slab": stats.Memory.Slab,
  1431. "sock": stats.Memory.Sock,
  1432. "shmem": stats.Memory.Shmem,
  1433. "file_mapped": stats.Memory.FileMapped,
  1434. "file_dirty": stats.Memory.FileDirty,
  1435. "file_writeback": stats.Memory.FileWriteback,
  1436. "anon_thp": stats.Memory.AnonThp,
  1437. "inactive_anon": stats.Memory.InactiveAnon,
  1438. "active_anon": stats.Memory.ActiveAnon,
  1439. "inactive_file": stats.Memory.InactiveFile,
  1440. "active_file": stats.Memory.ActiveFile,
  1441. "unevictable": stats.Memory.Unevictable,
  1442. "slab_reclaimable": stats.Memory.SlabReclaimable,
  1443. "slab_unreclaimable": stats.Memory.SlabUnreclaimable,
  1444. "pgfault": stats.Memory.Pgfault,
  1445. "pgmajfault": stats.Memory.Pgmajfault,
  1446. "workingset_refault": stats.Memory.WorkingsetRefault,
  1447. "workingset_activate": stats.Memory.WorkingsetActivate,
  1448. "workingset_nodereclaim": stats.Memory.WorkingsetNodereclaim,
  1449. "pgrefill": stats.Memory.Pgrefill,
  1450. "pgscan": stats.Memory.Pgscan,
  1451. "pgsteal": stats.Memory.Pgsteal,
  1452. "pgactivate": stats.Memory.Pgactivate,
  1453. "pgdeactivate": stats.Memory.Pgdeactivate,
  1454. "pglazyfree": stats.Memory.Pglazyfree,
  1455. "pglazyfreed": stats.Memory.Pglazyfreed,
  1456. "thp_fault_alloc": stats.Memory.ThpFaultAlloc,
  1457. "thp_collapse_alloc": stats.Memory.ThpCollapseAlloc,
  1458. },
  1459. Usage: stats.Memory.Usage,
  1460. // MaxUsage is not supported
  1461. Limit: stats.Memory.UsageLimit,
  1462. }
  1463. // if the container does not set memory limit, use the machineMemory
  1464. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1465. s.MemoryStats.Limit = daemon.machineMemory
  1466. }
  1467. if stats.MemoryEvents != nil {
  1468. // Failcnt is set to the "oom" field of the "memory.events" file.
  1469. // See https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
  1470. s.MemoryStats.Failcnt = stats.MemoryEvents.Oom
  1471. }
  1472. }
  1473. if stats.Pids != nil {
  1474. s.PidsStats = types.PidsStats{
  1475. Current: stats.Pids.Current,
  1476. Limit: stats.Pids.Limit,
  1477. }
  1478. }
  1479. return s, nil
  1480. }
  1481. // setDefaultIsolation determines the default isolation mode for the
  1482. // daemon to run in. This is only applicable on Windows
  1483. func (daemon *Daemon) setDefaultIsolation() error {
  1484. return nil
  1485. }
  1486. // setupDaemonProcess sets various settings for the daemon's process
  1487. func setupDaemonProcess(config *config.Config) error {
  1488. // setup the daemons oom_score_adj
  1489. if err := setupOOMScoreAdj(config.OOMScoreAdjust); err != nil {
  1490. return err
  1491. }
  1492. if err := setMayDetachMounts(); err != nil {
  1493. logrus.WithError(err).Warn("Could not set may_detach_mounts kernel parameter")
  1494. }
  1495. return nil
  1496. }
  1497. // This is used to allow removal of mountpoints that may be mounted in other
  1498. // namespaces on RHEL based kernels starting from RHEL 7.4.
  1499. // Without this setting, removals on these RHEL based kernels may fail with
  1500. // "device or resource busy".
  1501. // This setting is not available in upstream kernels as it is not configurable,
  1502. // but has been in the upstream kernels since 3.15.
  1503. func setMayDetachMounts() error {
  1504. f, err := os.OpenFile("/proc/sys/fs/may_detach_mounts", os.O_WRONLY, 0)
  1505. if err != nil {
  1506. if os.IsNotExist(err) {
  1507. return nil
  1508. }
  1509. return errors.Wrap(err, "error opening may_detach_mounts kernel config file")
  1510. }
  1511. defer f.Close()
  1512. _, err = f.WriteString("1")
  1513. if os.IsPermission(err) {
  1514. // Setting may_detach_mounts does not work in an
  1515. // unprivileged container. Ignore the error, but log
  1516. // it if we appear not to be in that situation.
  1517. if !userns.RunningInUserNS() {
  1518. logrus.Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
  1519. }
  1520. return nil
  1521. }
  1522. return err
  1523. }
  1524. func setupOOMScoreAdj(score int) error {
  1525. if score == 0 {
  1526. return nil
  1527. }
  1528. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1529. if err != nil {
  1530. return err
  1531. }
  1532. defer f.Close()
  1533. stringScore := strconv.Itoa(score)
  1534. _, err = f.WriteString(stringScore)
  1535. if os.IsPermission(err) {
  1536. // Setting oom_score_adj does not work in an
  1537. // unprivileged container. Ignore the error, but log
  1538. // it if we appear not to be in that situation.
  1539. if !userns.RunningInUserNS() {
  1540. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1541. }
  1542. return nil
  1543. }
  1544. return err
  1545. }
  1546. func (daemon *Daemon) initCPURtController(mnt, path string) error {
  1547. if path == "/" || path == "." {
  1548. return nil
  1549. }
  1550. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1551. // for the period and runtime as this limits what the children can be set to.
  1552. if err := daemon.initCPURtController(mnt, filepath.Dir(path)); err != nil {
  1553. return err
  1554. }
  1555. path = filepath.Join(mnt, path)
  1556. if err := os.MkdirAll(path, 0755); err != nil {
  1557. return err
  1558. }
  1559. if err := maybeCreateCPURealTimeFile(daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1560. return err
  1561. }
  1562. return maybeCreateCPURealTimeFile(daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path)
  1563. }
  1564. func maybeCreateCPURealTimeFile(configValue int64, file string, path string) error {
  1565. if configValue == 0 {
  1566. return nil
  1567. }
  1568. return os.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700)
  1569. }
  1570. func (daemon *Daemon) setupSeccompProfile() error {
  1571. switch profile := daemon.configStore.SeccompProfile; profile {
  1572. case "", config.SeccompProfileDefault:
  1573. daemon.seccompProfilePath = config.SeccompProfileDefault
  1574. case config.SeccompProfileUnconfined:
  1575. daemon.seccompProfilePath = config.SeccompProfileUnconfined
  1576. default:
  1577. daemon.seccompProfilePath = profile
  1578. b, err := os.ReadFile(profile)
  1579. if err != nil {
  1580. return fmt.Errorf("opening seccomp profile (%s) failed: %v", profile, err)
  1581. }
  1582. daemon.seccompProfile = b
  1583. }
  1584. return nil
  1585. }
  1586. func getSysInfo(daemon *Daemon) *sysinfo.SysInfo {
  1587. var siOpts []sysinfo.Opt
  1588. if daemon.getCgroupDriver() == cgroupSystemdDriver {
  1589. if euid := os.Getenv("ROOTLESSKIT_PARENT_EUID"); euid != "" {
  1590. siOpts = append(siOpts, sysinfo.WithCgroup2GroupPath("/user.slice/user-"+euid+".slice"))
  1591. }
  1592. }
  1593. return sysinfo.New(siOpts...)
  1594. }
  1595. func (daemon *Daemon) initLibcontainerd(ctx context.Context) error {
  1596. var err error
  1597. daemon.containerd, err = remote.NewClient(
  1598. ctx,
  1599. daemon.containerdCli,
  1600. filepath.Join(daemon.configStore.ExecRoot, "containerd"),
  1601. daemon.configStore.ContainerdNamespace,
  1602. daemon,
  1603. )
  1604. return err
  1605. }
  1606. func recursiveUnmount(target string) error {
  1607. return mount.RecursiveUnmount(target)
  1608. }