daemon_unix.go 55 KB

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