daemon_unix.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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/ioutils"
  31. "github.com/docker/docker/pkg/parsers"
  32. "github.com/docker/docker/pkg/parsers/kernel"
  33. "github.com/docker/docker/pkg/sysinfo"
  34. "github.com/docker/docker/runconfig"
  35. volumemounts "github.com/docker/docker/volume/mounts"
  36. "github.com/docker/libnetwork"
  37. nwconfig "github.com/docker/libnetwork/config"
  38. "github.com/docker/libnetwork/drivers/bridge"
  39. "github.com/docker/libnetwork/netlabel"
  40. "github.com/docker/libnetwork/netutils"
  41. "github.com/docker/libnetwork/options"
  42. lntypes "github.com/docker/libnetwork/types"
  43. "github.com/moby/sys/mount"
  44. "github.com/opencontainers/runc/libcontainer/cgroups"
  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. if getCD(config) == cgroupSystemdDriver {
  573. return true
  574. }
  575. // On cgroup v2 hosts, default to systemd driver
  576. if getCD(config) == "" && cgroups.IsCgroup2UnifiedMode() && IsRunningSystemd() {
  577. return true
  578. }
  579. return false
  580. }
  581. // IsRunningSystemd is from https://github.com/opencontainers/runc/blob/46be7b612e2533c494e6a251111de46d8e286ed5/libcontainer/cgroups/systemd/common.go#L27-L33
  582. func IsRunningSystemd() bool {
  583. fi, err := os.Lstat("/run/systemd/system")
  584. if err != nil {
  585. return false
  586. }
  587. return fi.IsDir()
  588. }
  589. // verifyPlatformContainerSettings performs platform-specific validation of the
  590. // hostconfig and config structures.
  591. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, update bool) (warnings []string, err error) {
  592. if hostConfig == nil {
  593. return nil, nil
  594. }
  595. sysInfo := daemon.RawSysInfo(true)
  596. w, err := verifyPlatformContainerResources(&hostConfig.Resources, sysInfo, update)
  597. // no matter err is nil or not, w could have data in itself.
  598. warnings = append(warnings, w...)
  599. if err != nil {
  600. return warnings, err
  601. }
  602. if hostConfig.ShmSize < 0 {
  603. return warnings, fmt.Errorf("SHM size can not be less than 0")
  604. }
  605. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  606. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  607. }
  608. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  609. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  610. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  611. }
  612. if hostConfig.NetworkMode.IsHost() && len(hostConfig.PortBindings) > 0 {
  613. warnings = append(warnings, "Published ports are discarded when using host network mode")
  614. }
  615. // check for various conflicting options with user namespaces
  616. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  617. if hostConfig.Privileged {
  618. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  619. }
  620. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  621. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  622. }
  623. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  624. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  625. }
  626. }
  627. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  628. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  629. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  630. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  631. }
  632. }
  633. if hostConfig.Runtime == "" {
  634. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  635. }
  636. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  637. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  638. }
  639. parser := volumemounts.NewParser(runtime.GOOS)
  640. for dest := range hostConfig.Tmpfs {
  641. if err := parser.ValidateTmpfsMountDestination(dest); err != nil {
  642. return warnings, err
  643. }
  644. }
  645. if !hostConfig.CgroupnsMode.Valid() {
  646. return warnings, fmt.Errorf("invalid cgroup namespace mode: %v", hostConfig.CgroupnsMode)
  647. }
  648. if hostConfig.CgroupnsMode.IsPrivate() {
  649. if !sysInfo.CgroupNamespaces {
  650. warnings = append(warnings, "Your kernel does not support cgroup namespaces. Cgroup namespace setting discarded.")
  651. }
  652. }
  653. return warnings, nil
  654. }
  655. func (daemon *Daemon) loadRuntimes() error {
  656. return daemon.initRuntimes(daemon.configStore.Runtimes)
  657. }
  658. func (daemon *Daemon) initRuntimes(runtimes map[string]types.Runtime) (err error) {
  659. runtimeDir := filepath.Join(daemon.configStore.Root, "runtimes")
  660. // Remove old temp directory if any
  661. os.RemoveAll(runtimeDir + "-old")
  662. tmpDir, err := ioutils.TempDir(daemon.configStore.Root, "gen-runtimes")
  663. if err != nil {
  664. return errors.Wrap(err, "failed to get temp dir to generate runtime scripts")
  665. }
  666. defer func() {
  667. if err != nil {
  668. if err1 := os.RemoveAll(tmpDir); err1 != nil {
  669. logrus.WithError(err1).WithField("dir", tmpDir).
  670. Warn("failed to remove tmp dir")
  671. }
  672. return
  673. }
  674. if err = os.Rename(runtimeDir, runtimeDir+"-old"); err != nil {
  675. return
  676. }
  677. if err = os.Rename(tmpDir, runtimeDir); err != nil {
  678. err = errors.Wrap(err, "failed to setup runtimes dir, new containers may not start")
  679. return
  680. }
  681. if err = os.RemoveAll(runtimeDir + "-old"); err != nil {
  682. logrus.WithError(err).WithField("dir", tmpDir).
  683. Warn("failed to remove old runtimes dir")
  684. }
  685. }()
  686. for name, rt := range runtimes {
  687. if len(rt.Args) == 0 {
  688. continue
  689. }
  690. script := filepath.Join(tmpDir, name)
  691. content := fmt.Sprintf("#!/bin/sh\n%s %s $@\n", rt.Path, strings.Join(rt.Args, " "))
  692. if err := ioutil.WriteFile(script, []byte(content), 0700); err != nil {
  693. return err
  694. }
  695. }
  696. return nil
  697. }
  698. // verifyDaemonSettings performs validation of daemon config struct
  699. func verifyDaemonSettings(conf *config.Config) error {
  700. if conf.ContainerdNamespace == conf.ContainerdPluginNamespace {
  701. return errors.New("containers namespace and plugins namespace cannot be the same")
  702. }
  703. // Check for mutually incompatible config options
  704. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  705. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  706. }
  707. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  708. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  709. }
  710. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  711. conf.BridgeConfig.EnableIPMasq = false
  712. }
  713. if err := VerifyCgroupDriver(conf); err != nil {
  714. return err
  715. }
  716. if conf.CgroupParent != "" && UsingSystemd(conf) {
  717. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  718. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  719. }
  720. }
  721. if conf.Rootless && UsingSystemd(conf) && !cgroups.IsCgroup2UnifiedMode() {
  722. return fmt.Errorf("exec-opt native.cgroupdriver=systemd requires cgroup v2 for rootless mode")
  723. }
  724. if conf.DefaultRuntime == "" {
  725. conf.DefaultRuntime = config.StockRuntimeName
  726. }
  727. if conf.Runtimes == nil {
  728. conf.Runtimes = make(map[string]types.Runtime)
  729. }
  730. conf.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeName}
  731. return nil
  732. }
  733. // checkSystem validates platform-specific requirements
  734. func checkSystem() error {
  735. return checkKernel()
  736. }
  737. // configureMaxThreads sets the Go runtime max threads threshold
  738. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  739. func configureMaxThreads(config *config.Config) error {
  740. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  741. if err != nil {
  742. return err
  743. }
  744. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  745. if err != nil {
  746. return err
  747. }
  748. maxThreads := (mtint / 100) * 90
  749. debug.SetMaxThreads(maxThreads)
  750. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  751. return nil
  752. }
  753. func overlaySupportsSelinux() (bool, error) {
  754. f, err := os.Open("/proc/kallsyms")
  755. if err != nil {
  756. if os.IsNotExist(err) {
  757. return false, nil
  758. }
  759. return false, err
  760. }
  761. defer f.Close()
  762. s := bufio.NewScanner(f)
  763. for s.Scan() {
  764. if strings.HasSuffix(s.Text(), " security_inode_copy_up") {
  765. return true, nil
  766. }
  767. }
  768. return false, s.Err()
  769. }
  770. // configureKernelSecuritySupport configures and validates security support for the kernel
  771. func configureKernelSecuritySupport(config *config.Config, driverName string) error {
  772. if config.EnableSelinuxSupport {
  773. if !selinuxEnabled() {
  774. logrus.Warn("Docker could not enable SELinux on the host system")
  775. return nil
  776. }
  777. if driverName == "overlay" || driverName == "overlay2" {
  778. // If driver is overlay or overlay2, make sure kernel
  779. // supports selinux with overlay.
  780. supported, err := overlaySupportsSelinux()
  781. if err != nil {
  782. return err
  783. }
  784. if !supported {
  785. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverName)
  786. }
  787. }
  788. } else {
  789. selinuxSetDisabled()
  790. }
  791. return nil
  792. }
  793. func (daemon *Daemon) initNetworkController(config *config.Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  794. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  795. if err != nil {
  796. return nil, err
  797. }
  798. controller, err := libnetwork.New(netOptions...)
  799. if err != nil {
  800. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  801. }
  802. if len(activeSandboxes) > 0 {
  803. logrus.Info("There are old running containers, the network config will not take affect")
  804. return controller, nil
  805. }
  806. // Initialize default network on "null"
  807. if n, _ := controller.NetworkByName("none"); n == nil {
  808. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  809. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  810. }
  811. }
  812. // Initialize default network on "host"
  813. if n, _ := controller.NetworkByName("host"); n == nil {
  814. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  815. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  816. }
  817. }
  818. // Clear stale bridge network
  819. if n, err := controller.NetworkByName("bridge"); err == nil {
  820. if err = n.Delete(); err != nil {
  821. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  822. }
  823. if len(config.NetworkConfig.DefaultAddressPools.Value()) > 0 && !daemon.configStore.LiveRestoreEnabled {
  824. removeDefaultBridgeInterface()
  825. }
  826. }
  827. if !config.DisableBridge {
  828. // Initialize default driver "bridge"
  829. if err := initBridgeDriver(controller, config); err != nil {
  830. return nil, err
  831. }
  832. } else {
  833. removeDefaultBridgeInterface()
  834. }
  835. // Set HostGatewayIP to the default bridge's IP if it is empty
  836. if daemon.configStore.HostGatewayIP == nil && controller != nil {
  837. if n, err := controller.NetworkByName("bridge"); err == nil {
  838. v4Info, v6Info := n.Info().IpamInfo()
  839. var gateway net.IP
  840. if len(v4Info) > 0 {
  841. gateway = v4Info[0].Gateway.IP
  842. } else if len(v6Info) > 0 {
  843. gateway = v6Info[0].Gateway.IP
  844. }
  845. daemon.configStore.HostGatewayIP = gateway
  846. }
  847. }
  848. return controller, nil
  849. }
  850. func driverOptions(config *config.Config) []nwconfig.Option {
  851. bridgeConfig := options.Generic{
  852. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  853. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  854. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  855. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath}
  856. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  857. dOptions := []nwconfig.Option{}
  858. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  859. return dOptions
  860. }
  861. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  862. bridgeName := bridge.DefaultBridgeName
  863. if config.BridgeConfig.Iface != "" {
  864. bridgeName = config.BridgeConfig.Iface
  865. }
  866. netOption := map[string]string{
  867. bridge.BridgeName: bridgeName,
  868. bridge.DefaultBridge: strconv.FormatBool(true),
  869. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  870. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  871. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  872. }
  873. // --ip processing
  874. if config.BridgeConfig.DefaultIP != nil {
  875. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  876. }
  877. ipamV4Conf := &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  878. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  879. if err != nil {
  880. return errors.Wrap(err, "list bridge addresses failed")
  881. }
  882. nw := nwList[0]
  883. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  884. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  885. if err != nil {
  886. return errors.Wrap(err, "parse CIDR failed")
  887. }
  888. // Iterate through in case there are multiple addresses for the bridge
  889. for _, entry := range nwList {
  890. if fCIDR.Contains(entry.IP) {
  891. nw = entry
  892. break
  893. }
  894. }
  895. }
  896. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  897. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  898. if hip.IsGlobalUnicast() {
  899. ipamV4Conf.Gateway = nw.IP.String()
  900. }
  901. if config.BridgeConfig.IP != "" {
  902. ip, ipNet, err := net.ParseCIDR(config.BridgeConfig.IP)
  903. if err != nil {
  904. return err
  905. }
  906. ipamV4Conf.PreferredPool = ipNet.String()
  907. ipamV4Conf.Gateway = ip.String()
  908. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  909. 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)
  910. }
  911. if config.BridgeConfig.FixedCIDR != "" {
  912. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  913. if err != nil {
  914. return err
  915. }
  916. ipamV4Conf.SubPool = fCIDR.String()
  917. }
  918. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  919. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  920. }
  921. var (
  922. deferIPv6Alloc bool
  923. ipamV6Conf *libnetwork.IpamConf
  924. )
  925. if config.BridgeConfig.EnableIPv6 && config.BridgeConfig.FixedCIDRv6 == "" {
  926. 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"))
  927. } else if config.BridgeConfig.FixedCIDRv6 != "" {
  928. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  929. if err != nil {
  930. return err
  931. }
  932. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  933. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  934. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  935. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  936. // on this network until after the driver has created the endpoint and returned the
  937. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  938. ones, _ := fCIDRv6.Mask.Size()
  939. deferIPv6Alloc = ones <= 80
  940. ipamV6Conf = &libnetwork.IpamConf{
  941. AuxAddresses: make(map[string]string),
  942. PreferredPool: fCIDRv6.String(),
  943. }
  944. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  945. // address belongs to the same network, we need to inform libnetwork about it, so
  946. // that it can be reserved with IPAM and it will not be given away to somebody else
  947. for _, nw6 := range nw6List {
  948. if fCIDRv6.Contains(nw6.IP) {
  949. ipamV6Conf.Gateway = nw6.IP.String()
  950. break
  951. }
  952. }
  953. }
  954. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  955. if ipamV6Conf == nil {
  956. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  957. }
  958. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  959. }
  960. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  961. v6Conf := []*libnetwork.IpamConf{}
  962. if ipamV6Conf != nil {
  963. v6Conf = append(v6Conf, ipamV6Conf)
  964. }
  965. // Initialize default network on "bridge" with the same name
  966. _, err = controller.NewNetwork("bridge", "bridge", "",
  967. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  968. libnetwork.NetworkOptionDriverOpts(netOption),
  969. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  970. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  971. if err != nil {
  972. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  973. }
  974. return nil
  975. }
  976. // Remove default bridge interface if present (--bridge=none use case)
  977. func removeDefaultBridgeInterface() {
  978. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  979. if err := netlink.LinkDel(lnk); err != nil {
  980. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  981. }
  982. }
  983. }
  984. func setupInitLayer(idMapping *idtools.IdentityMapping) func(containerfs.ContainerFS) error {
  985. return func(initPath containerfs.ContainerFS) error {
  986. return initlayer.Setup(initPath, idMapping.RootPair())
  987. }
  988. }
  989. // Parse the remapped root (user namespace) option, which can be one of:
  990. // username - valid username from /etc/passwd
  991. // username:groupname - valid username; valid groupname from /etc/group
  992. // uid - 32-bit unsigned int valid Linux UID value
  993. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  994. //
  995. // If no groupname is specified, and a username is specified, an attempt
  996. // will be made to lookup a gid for that username as a groupname
  997. //
  998. // If names are used, they are verified to exist in passwd/group
  999. func parseRemappedRoot(usergrp string) (string, string, error) {
  1000. var (
  1001. userID, groupID int
  1002. username, groupname string
  1003. )
  1004. idparts := strings.Split(usergrp, ":")
  1005. if len(idparts) > 2 {
  1006. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  1007. }
  1008. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  1009. // must be a uid; take it as valid
  1010. userID = int(uid)
  1011. luser, err := idtools.LookupUID(userID)
  1012. if err != nil {
  1013. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  1014. }
  1015. username = luser.Name
  1016. if len(idparts) == 1 {
  1017. // if the uid was numeric and no gid was specified, take the uid as the gid
  1018. groupID = userID
  1019. lgrp, err := idtools.LookupGID(groupID)
  1020. if err != nil {
  1021. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  1022. }
  1023. groupname = lgrp.Name
  1024. }
  1025. } else {
  1026. lookupName := idparts[0]
  1027. // special case: if the user specified "default", they want Docker to create or
  1028. // use (after creation) the "dockremap" user/group for root remapping
  1029. if lookupName == defaultIDSpecifier {
  1030. lookupName = defaultRemappedID
  1031. }
  1032. luser, err := idtools.LookupUser(lookupName)
  1033. if err != nil && idparts[0] != defaultIDSpecifier {
  1034. // error if the name requested isn't the special "dockremap" ID
  1035. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  1036. } else if err != nil {
  1037. // special case-- if the username == "default", then we have been asked
  1038. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  1039. // ranges will be used for the user and group mappings in user namespaced containers
  1040. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  1041. if err == nil {
  1042. return defaultRemappedID, defaultRemappedID, nil
  1043. }
  1044. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  1045. }
  1046. username = luser.Name
  1047. if len(idparts) == 1 {
  1048. // we only have a string username, and no group specified; look up gid from username as group
  1049. group, err := idtools.LookupGroup(lookupName)
  1050. if err != nil {
  1051. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  1052. }
  1053. groupname = group.Name
  1054. }
  1055. }
  1056. if len(idparts) == 2 {
  1057. // groupname or gid is separately specified and must be resolved
  1058. // to an unsigned 32-bit gid
  1059. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  1060. // must be a gid, take it as valid
  1061. groupID = int(gid)
  1062. lgrp, err := idtools.LookupGID(groupID)
  1063. if err != nil {
  1064. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  1065. }
  1066. groupname = lgrp.Name
  1067. } else {
  1068. // not a number; attempt a lookup
  1069. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  1070. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  1071. }
  1072. groupname = idparts[1]
  1073. }
  1074. }
  1075. return username, groupname, nil
  1076. }
  1077. func setupRemappedRoot(config *config.Config) (*idtools.IdentityMapping, error) {
  1078. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  1079. return nil, fmt.Errorf("User namespaces are only supported on Linux")
  1080. }
  1081. // if the daemon was started with remapped root option, parse
  1082. // the config option to the int uid,gid values
  1083. if config.RemappedRoot != "" {
  1084. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  1085. if err != nil {
  1086. return nil, err
  1087. }
  1088. if username == "root" {
  1089. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  1090. // effectively
  1091. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  1092. return &idtools.IdentityMapping{}, nil
  1093. }
  1094. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s", username)
  1095. // update remapped root setting now that we have resolved them to actual names
  1096. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  1097. mappings, err := idtools.NewIdentityMapping(username)
  1098. if err != nil {
  1099. return nil, errors.Wrap(err, "Can't create ID mappings")
  1100. }
  1101. return mappings, nil
  1102. }
  1103. return &idtools.IdentityMapping{}, nil
  1104. }
  1105. func setupDaemonRoot(config *config.Config, rootDir string, rootIdentity idtools.Identity) error {
  1106. config.Root = rootDir
  1107. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  1108. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  1109. // (e.g. mounted layers of a container) can traverse this path.
  1110. // The user namespace support will create subdirectories for the remapped root host uid:gid
  1111. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  1112. // layer content subtrees.
  1113. if _, err := os.Stat(rootDir); err == nil {
  1114. // root current exists; verify the access bits are correct by setting them
  1115. if err = os.Chmod(rootDir, 0711); err != nil {
  1116. return err
  1117. }
  1118. } else if os.IsNotExist(err) {
  1119. // no root exists yet, create it 0711 with root:root ownership
  1120. if err := os.MkdirAll(rootDir, 0711); err != nil {
  1121. return err
  1122. }
  1123. }
  1124. // if user namespaces are enabled we will create a subtree underneath the specified root
  1125. // with any/all specified remapped root uid/gid options on the daemon creating
  1126. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  1127. // `chdir()` to work for containers namespaced to that uid/gid)
  1128. if config.RemappedRoot != "" {
  1129. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootIdentity.UID, rootIdentity.GID))
  1130. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  1131. // Create the root directory if it doesn't exist
  1132. if err := idtools.MkdirAllAndChown(config.Root, 0700, rootIdentity); err != nil {
  1133. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  1134. }
  1135. // we also need to verify that any pre-existing directories in the path to
  1136. // the graphroot won't block access to remapped root--if any pre-existing directory
  1137. // has strict permissions that don't allow "x", container start will fail, so
  1138. // better to warn and fail now
  1139. dirPath := config.Root
  1140. for {
  1141. dirPath = filepath.Dir(dirPath)
  1142. if dirPath == "/" {
  1143. break
  1144. }
  1145. if !idtools.CanAccess(dirPath, rootIdentity) {
  1146. 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)
  1147. }
  1148. }
  1149. }
  1150. if err := setupDaemonRootPropagation(config); err != nil {
  1151. 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")
  1152. }
  1153. return nil
  1154. }
  1155. func setupDaemonRootPropagation(cfg *config.Config) error {
  1156. rootParentMount, mountOptions, err := getSourceMount(cfg.Root)
  1157. if err != nil {
  1158. return errors.Wrap(err, "error getting daemon root's parent mount")
  1159. }
  1160. var cleanupOldFile bool
  1161. cleanupFile := getUnmountOnShutdownPath(cfg)
  1162. defer func() {
  1163. if !cleanupOldFile {
  1164. return
  1165. }
  1166. if err := os.Remove(cleanupFile); err != nil && !os.IsNotExist(err) {
  1167. logrus.WithError(err).WithField("file", cleanupFile).Warn("could not clean up old root propagation unmount file")
  1168. }
  1169. }()
  1170. if hasMountInfoOption(mountOptions, sharedPropagationOption, slavePropagationOption) {
  1171. cleanupOldFile = true
  1172. return nil
  1173. }
  1174. if err := mount.MakeShared(cfg.Root); err != nil {
  1175. return errors.Wrap(err, "could not setup daemon root propagation to shared")
  1176. }
  1177. // check the case where this may have already been a mount to itself.
  1178. // If so then the daemon only performed a remount and should not try to unmount this later.
  1179. if rootParentMount == cfg.Root {
  1180. cleanupOldFile = true
  1181. return nil
  1182. }
  1183. if err := os.MkdirAll(filepath.Dir(cleanupFile), 0700); err != nil {
  1184. return errors.Wrap(err, "error creating dir to store mount cleanup file")
  1185. }
  1186. if err := ioutil.WriteFile(cleanupFile, nil, 0600); err != nil {
  1187. return errors.Wrap(err, "error writing file to signal mount cleanup on shutdown")
  1188. }
  1189. return nil
  1190. }
  1191. // getUnmountOnShutdownPath generates the path to used when writing the file that signals to the daemon that on shutdown
  1192. // the daemon root should be unmounted.
  1193. func getUnmountOnShutdownPath(config *config.Config) string {
  1194. return filepath.Join(config.ExecRoot, "unmount-on-shutdown")
  1195. }
  1196. // registerLinks writes the links to a file.
  1197. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1198. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1199. return nil
  1200. }
  1201. for _, l := range hostConfig.Links {
  1202. name, alias, err := opts.ParseLink(l)
  1203. if err != nil {
  1204. return err
  1205. }
  1206. child, err := daemon.GetContainer(name)
  1207. if err != nil {
  1208. if errdefs.IsNotFound(err) {
  1209. // Trying to link to a non-existing container is not valid, and
  1210. // should return an "invalid parameter" error. Returning a "not
  1211. // found" error here would make the client report the container's
  1212. // image could not be found (see moby/moby#39823)
  1213. err = errdefs.InvalidParameter(err)
  1214. }
  1215. return errors.Wrapf(err, "could not get container for %s", name)
  1216. }
  1217. for child.HostConfig.NetworkMode.IsContainer() {
  1218. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  1219. child, err = daemon.GetContainer(parts[1])
  1220. if err != nil {
  1221. if errdefs.IsNotFound(err) {
  1222. // Trying to link to a non-existing container is not valid, and
  1223. // should return an "invalid parameter" error. Returning a "not
  1224. // found" error here would make the client report the container's
  1225. // image could not be found (see moby/moby#39823)
  1226. err = errdefs.InvalidParameter(err)
  1227. }
  1228. return errors.Wrapf(err, "Could not get container for %s", parts[1])
  1229. }
  1230. }
  1231. if child.HostConfig.NetworkMode.IsHost() {
  1232. return runconfig.ErrConflictHostNetworkAndLinks
  1233. }
  1234. if err := daemon.registerLink(container, child, alias); err != nil {
  1235. return err
  1236. }
  1237. }
  1238. // After we load all the links into the daemon
  1239. // set them to nil on the hostconfig
  1240. _, err := container.WriteHostConfig()
  1241. return err
  1242. }
  1243. // conditionalMountOnStart is a platform specific helper function during the
  1244. // container start to call mount.
  1245. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1246. return daemon.Mount(container)
  1247. }
  1248. // conditionalUnmountOnCleanup is a platform specific helper function called
  1249. // during the cleanup of a container to unmount.
  1250. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1251. return daemon.Unmount(container)
  1252. }
  1253. func copyBlkioEntry(entries []*statsV1.BlkIOEntry) []types.BlkioStatEntry {
  1254. out := make([]types.BlkioStatEntry, len(entries))
  1255. for i, re := range entries {
  1256. out[i] = types.BlkioStatEntry{
  1257. Major: re.Major,
  1258. Minor: re.Minor,
  1259. Op: re.Op,
  1260. Value: re.Value,
  1261. }
  1262. }
  1263. return out
  1264. }
  1265. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1266. if !c.IsRunning() {
  1267. return nil, errNotRunning(c.ID)
  1268. }
  1269. cs, err := daemon.containerd.Stats(context.Background(), c.ID)
  1270. if err != nil {
  1271. if strings.Contains(err.Error(), "container not found") {
  1272. return nil, containerNotFound(c.ID)
  1273. }
  1274. return nil, err
  1275. }
  1276. s := &types.StatsJSON{}
  1277. s.Read = cs.Read
  1278. stats := cs.Metrics
  1279. switch t := stats.(type) {
  1280. case *statsV1.Metrics:
  1281. return daemon.statsV1(s, t)
  1282. case *statsV2.Metrics:
  1283. return daemon.statsV2(s, t)
  1284. default:
  1285. return nil, errors.Errorf("unexpected type of metrics %+v", t)
  1286. }
  1287. }
  1288. func (daemon *Daemon) statsV1(s *types.StatsJSON, stats *statsV1.Metrics) (*types.StatsJSON, error) {
  1289. if stats.Blkio != nil {
  1290. s.BlkioStats = types.BlkioStats{
  1291. IoServiceBytesRecursive: copyBlkioEntry(stats.Blkio.IoServiceBytesRecursive),
  1292. IoServicedRecursive: copyBlkioEntry(stats.Blkio.IoServicedRecursive),
  1293. IoQueuedRecursive: copyBlkioEntry(stats.Blkio.IoQueuedRecursive),
  1294. IoServiceTimeRecursive: copyBlkioEntry(stats.Blkio.IoServiceTimeRecursive),
  1295. IoWaitTimeRecursive: copyBlkioEntry(stats.Blkio.IoWaitTimeRecursive),
  1296. IoMergedRecursive: copyBlkioEntry(stats.Blkio.IoMergedRecursive),
  1297. IoTimeRecursive: copyBlkioEntry(stats.Blkio.IoTimeRecursive),
  1298. SectorsRecursive: copyBlkioEntry(stats.Blkio.SectorsRecursive),
  1299. }
  1300. }
  1301. if stats.CPU != nil {
  1302. s.CPUStats = types.CPUStats{
  1303. CPUUsage: types.CPUUsage{
  1304. TotalUsage: stats.CPU.Usage.Total,
  1305. PercpuUsage: stats.CPU.Usage.PerCPU,
  1306. UsageInKernelmode: stats.CPU.Usage.Kernel,
  1307. UsageInUsermode: stats.CPU.Usage.User,
  1308. },
  1309. ThrottlingData: types.ThrottlingData{
  1310. Periods: stats.CPU.Throttling.Periods,
  1311. ThrottledPeriods: stats.CPU.Throttling.ThrottledPeriods,
  1312. ThrottledTime: stats.CPU.Throttling.ThrottledTime,
  1313. },
  1314. }
  1315. }
  1316. if stats.Memory != nil {
  1317. raw := make(map[string]uint64)
  1318. raw["cache"] = stats.Memory.Cache
  1319. raw["rss"] = stats.Memory.RSS
  1320. raw["rss_huge"] = stats.Memory.RSSHuge
  1321. raw["mapped_file"] = stats.Memory.MappedFile
  1322. raw["dirty"] = stats.Memory.Dirty
  1323. raw["writeback"] = stats.Memory.Writeback
  1324. raw["pgpgin"] = stats.Memory.PgPgIn
  1325. raw["pgpgout"] = stats.Memory.PgPgOut
  1326. raw["pgfault"] = stats.Memory.PgFault
  1327. raw["pgmajfault"] = stats.Memory.PgMajFault
  1328. raw["inactive_anon"] = stats.Memory.InactiveAnon
  1329. raw["active_anon"] = stats.Memory.ActiveAnon
  1330. raw["inactive_file"] = stats.Memory.InactiveFile
  1331. raw["active_file"] = stats.Memory.ActiveFile
  1332. raw["unevictable"] = stats.Memory.Unevictable
  1333. raw["hierarchical_memory_limit"] = stats.Memory.HierarchicalMemoryLimit
  1334. raw["hierarchical_memsw_limit"] = stats.Memory.HierarchicalSwapLimit
  1335. raw["total_cache"] = stats.Memory.TotalCache
  1336. raw["total_rss"] = stats.Memory.TotalRSS
  1337. raw["total_rss_huge"] = stats.Memory.TotalRSSHuge
  1338. raw["total_mapped_file"] = stats.Memory.TotalMappedFile
  1339. raw["total_dirty"] = stats.Memory.TotalDirty
  1340. raw["total_writeback"] = stats.Memory.TotalWriteback
  1341. raw["total_pgpgin"] = stats.Memory.TotalPgPgIn
  1342. raw["total_pgpgout"] = stats.Memory.TotalPgPgOut
  1343. raw["total_pgfault"] = stats.Memory.TotalPgFault
  1344. raw["total_pgmajfault"] = stats.Memory.TotalPgMajFault
  1345. raw["total_inactive_anon"] = stats.Memory.TotalInactiveAnon
  1346. raw["total_active_anon"] = stats.Memory.TotalActiveAnon
  1347. raw["total_inactive_file"] = stats.Memory.TotalInactiveFile
  1348. raw["total_active_file"] = stats.Memory.TotalActiveFile
  1349. raw["total_unevictable"] = stats.Memory.TotalUnevictable
  1350. if stats.Memory.Usage != nil {
  1351. s.MemoryStats = types.MemoryStats{
  1352. Stats: raw,
  1353. Usage: stats.Memory.Usage.Usage,
  1354. MaxUsage: stats.Memory.Usage.Max,
  1355. Limit: stats.Memory.Usage.Limit,
  1356. Failcnt: stats.Memory.Usage.Failcnt,
  1357. }
  1358. } else {
  1359. s.MemoryStats = types.MemoryStats{
  1360. Stats: raw,
  1361. }
  1362. }
  1363. // if the container does not set memory limit, use the machineMemory
  1364. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1365. s.MemoryStats.Limit = daemon.machineMemory
  1366. }
  1367. }
  1368. if stats.Pids != nil {
  1369. s.PidsStats = types.PidsStats{
  1370. Current: stats.Pids.Current,
  1371. Limit: stats.Pids.Limit,
  1372. }
  1373. }
  1374. return s, nil
  1375. }
  1376. func (daemon *Daemon) statsV2(s *types.StatsJSON, stats *statsV2.Metrics) (*types.StatsJSON, error) {
  1377. if stats.Io != nil {
  1378. var isbr []types.BlkioStatEntry
  1379. for _, re := range stats.Io.Usage {
  1380. isbr = append(isbr,
  1381. types.BlkioStatEntry{
  1382. Major: re.Major,
  1383. Minor: re.Minor,
  1384. Op: "read",
  1385. Value: re.Rbytes,
  1386. },
  1387. types.BlkioStatEntry{
  1388. Major: re.Major,
  1389. Minor: re.Minor,
  1390. Op: "write",
  1391. Value: re.Wbytes,
  1392. },
  1393. )
  1394. }
  1395. s.BlkioStats = types.BlkioStats{
  1396. IoServiceBytesRecursive: isbr,
  1397. // Other fields are unsupported
  1398. }
  1399. }
  1400. if stats.CPU != nil {
  1401. s.CPUStats = types.CPUStats{
  1402. CPUUsage: types.CPUUsage{
  1403. TotalUsage: stats.CPU.UsageUsec * 1000,
  1404. // PercpuUsage is not supported
  1405. UsageInKernelmode: stats.CPU.SystemUsec * 1000,
  1406. UsageInUsermode: stats.CPU.UserUsec * 1000,
  1407. },
  1408. ThrottlingData: types.ThrottlingData{
  1409. Periods: stats.CPU.NrPeriods,
  1410. ThrottledPeriods: stats.CPU.NrThrottled,
  1411. ThrottledTime: stats.CPU.ThrottledUsec * 1000,
  1412. },
  1413. }
  1414. }
  1415. if stats.Memory != nil {
  1416. raw := make(map[string]uint64)
  1417. raw["anon"] = stats.Memory.Anon
  1418. raw["file"] = stats.Memory.File
  1419. raw["kernel_stack"] = stats.Memory.KernelStack
  1420. raw["slab"] = stats.Memory.Slab
  1421. raw["sock"] = stats.Memory.Sock
  1422. raw["shmem"] = stats.Memory.Shmem
  1423. raw["file_mapped"] = stats.Memory.FileMapped
  1424. raw["file_dirty"] = stats.Memory.FileDirty
  1425. raw["file_writeback"] = stats.Memory.FileWriteback
  1426. raw["anon_thp"] = stats.Memory.AnonThp
  1427. raw["inactive_anon"] = stats.Memory.InactiveAnon
  1428. raw["active_anon"] = stats.Memory.ActiveAnon
  1429. raw["inactive_file"] = stats.Memory.InactiveFile
  1430. raw["active_file"] = stats.Memory.ActiveFile
  1431. raw["unevictable"] = stats.Memory.Unevictable
  1432. raw["slab_reclaimable"] = stats.Memory.SlabReclaimable
  1433. raw["slab_unreclaimable"] = stats.Memory.SlabUnreclaimable
  1434. raw["pgfault"] = stats.Memory.Pgfault
  1435. raw["pgmajfault"] = stats.Memory.Pgmajfault
  1436. raw["workingset_refault"] = stats.Memory.WorkingsetRefault
  1437. raw["workingset_activate"] = stats.Memory.WorkingsetActivate
  1438. raw["workingset_nodereclaim"] = stats.Memory.WorkingsetNodereclaim
  1439. raw["pgrefill"] = stats.Memory.Pgrefill
  1440. raw["pgscan"] = stats.Memory.Pgscan
  1441. raw["pgsteal"] = stats.Memory.Pgsteal
  1442. raw["pgactivate"] = stats.Memory.Pgactivate
  1443. raw["pgdeactivate"] = stats.Memory.Pgdeactivate
  1444. raw["pglazyfree"] = stats.Memory.Pglazyfree
  1445. raw["pglazyfreed"] = stats.Memory.Pglazyfreed
  1446. raw["thp_fault_alloc"] = stats.Memory.ThpFaultAlloc
  1447. raw["thp_collapse_alloc"] = stats.Memory.ThpCollapseAlloc
  1448. s.MemoryStats = types.MemoryStats{
  1449. // Stats is not compatible with v1
  1450. Stats: raw,
  1451. Usage: stats.Memory.Usage,
  1452. // MaxUsage is not supported
  1453. Limit: stats.Memory.UsageLimit,
  1454. // TODO: Failcnt
  1455. }
  1456. // if the container does not set memory limit, use the machineMemory
  1457. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1458. s.MemoryStats.Limit = daemon.machineMemory
  1459. }
  1460. }
  1461. if stats.Pids != nil {
  1462. s.PidsStats = types.PidsStats{
  1463. Current: stats.Pids.Current,
  1464. Limit: stats.Pids.Limit,
  1465. }
  1466. }
  1467. return s, nil
  1468. }
  1469. // setDefaultIsolation determines the default isolation mode for the
  1470. // daemon to run in. This is only applicable on Windows
  1471. func (daemon *Daemon) setDefaultIsolation() error {
  1472. return nil
  1473. }
  1474. // setupDaemonProcess sets various settings for the daemon's process
  1475. func setupDaemonProcess(config *config.Config) error {
  1476. // setup the daemons oom_score_adj
  1477. if err := setupOOMScoreAdj(config.OOMScoreAdjust); err != nil {
  1478. return err
  1479. }
  1480. if err := setMayDetachMounts(); err != nil {
  1481. logrus.WithError(err).Warn("Could not set may_detach_mounts kernel parameter")
  1482. }
  1483. return nil
  1484. }
  1485. // This is used to allow removal of mountpoints that may be mounted in other
  1486. // namespaces on RHEL based kernels starting from RHEL 7.4.
  1487. // Without this setting, removals on these RHEL based kernels may fail with
  1488. // "device or resource busy".
  1489. // This setting is not available in upstream kernels as it is not configurable,
  1490. // but has been in the upstream kernels since 3.15.
  1491. func setMayDetachMounts() error {
  1492. f, err := os.OpenFile("/proc/sys/fs/may_detach_mounts", os.O_WRONLY, 0)
  1493. if err != nil {
  1494. if os.IsNotExist(err) {
  1495. return nil
  1496. }
  1497. return errors.Wrap(err, "error opening may_detach_mounts kernel config file")
  1498. }
  1499. defer f.Close()
  1500. _, err = f.WriteString("1")
  1501. if os.IsPermission(err) {
  1502. // Setting may_detach_mounts does not work in an
  1503. // unprivileged container. Ignore the error, but log
  1504. // it if we appear not to be in that situation.
  1505. if !sys.RunningInUserNS() {
  1506. logrus.Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
  1507. }
  1508. return nil
  1509. }
  1510. return err
  1511. }
  1512. func setupOOMScoreAdj(score int) error {
  1513. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1514. if err != nil {
  1515. return err
  1516. }
  1517. defer f.Close()
  1518. stringScore := strconv.Itoa(score)
  1519. _, err = f.WriteString(stringScore)
  1520. if os.IsPermission(err) {
  1521. // Setting oom_score_adj does not work in an
  1522. // unprivileged container. Ignore the error, but log
  1523. // it if we appear not to be in that situation.
  1524. if !sys.RunningInUserNS() {
  1525. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1526. }
  1527. return nil
  1528. }
  1529. return err
  1530. }
  1531. func (daemon *Daemon) initCgroupsPath(path string) error {
  1532. if path == "/" || path == "." {
  1533. return nil
  1534. }
  1535. if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
  1536. return nil
  1537. }
  1538. if cgroups.IsCgroup2UnifiedMode() {
  1539. return fmt.Errorf("daemon-scoped cpu-rt-period and cpu-rt-runtime are not implemented for cgroup v2")
  1540. }
  1541. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1542. // for the period and runtime as this limits what the children can be set to.
  1543. daemon.initCgroupsPath(filepath.Dir(path))
  1544. mnt, root, err := cgroups.FindCgroupMountpointAndRoot("", "cpu")
  1545. if err != nil {
  1546. return err
  1547. }
  1548. // When docker is run inside docker, the root is based of the host cgroup.
  1549. // Should this be handled in runc/libcontainer/cgroups ?
  1550. if strings.HasPrefix(root, "/docker/") {
  1551. root = "/"
  1552. }
  1553. path = filepath.Join(mnt, root, path)
  1554. sysInfo := daemon.RawSysInfo(true)
  1555. if err := maybeCreateCPURealTimeFile(sysInfo.CPURealtimePeriod, daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1556. return err
  1557. }
  1558. return maybeCreateCPURealTimeFile(sysInfo.CPURealtimeRuntime, daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path)
  1559. }
  1560. func maybeCreateCPURealTimeFile(sysinfoPresent bool, configValue int64, file string, path string) error {
  1561. if sysinfoPresent && configValue != 0 {
  1562. if err := os.MkdirAll(path, 0755); err != nil {
  1563. return err
  1564. }
  1565. if err := ioutil.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700); err != nil {
  1566. return err
  1567. }
  1568. }
  1569. return nil
  1570. }
  1571. func (daemon *Daemon) setupSeccompProfile() error {
  1572. if daemon.configStore.SeccompProfile != "" {
  1573. daemon.seccompProfilePath = daemon.configStore.SeccompProfile
  1574. b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
  1575. if err != nil {
  1576. return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
  1577. }
  1578. daemon.seccompProfile = b
  1579. }
  1580. return nil
  1581. }
  1582. func (daemon *Daemon) useShimV2() bool {
  1583. return cgroups.IsCgroup2UnifiedMode()
  1584. }
  1585. // RawSysInfo returns *sysinfo.SysInfo .
  1586. func (daemon *Daemon) RawSysInfo(quiet bool) *sysinfo.SysInfo {
  1587. var opts []sysinfo.Opt
  1588. if daemon.getCgroupDriver() == cgroupSystemdDriver {
  1589. rootlesskitParentEUID := os.Getenv("ROOTLESSKIT_PARENT_EUID")
  1590. if rootlesskitParentEUID != "" {
  1591. groupPath := fmt.Sprintf("/user.slice/user-%s.slice", rootlesskitParentEUID)
  1592. opts = append(opts, sysinfo.WithCgroup2GroupPath(groupPath))
  1593. }
  1594. }
  1595. return sysinfo.New(quiet, opts...)
  1596. }