daemon_unix.go 57 KB

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