daemon_unix.go 62 KB

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