daemon_unix.go 54 KB

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