daemon_unix.go 64 KB

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