daemon_unix.go 64 KB

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