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