daemon_unix.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "runtime/debug"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/docker/docker/api/types"
  17. "github.com/docker/docker/api/types/blkiodev"
  18. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  19. containertypes "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/container"
  21. "github.com/docker/docker/daemon/config"
  22. "github.com/docker/docker/image"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/idtools"
  25. "github.com/docker/docker/pkg/parsers"
  26. "github.com/docker/docker/pkg/parsers/kernel"
  27. "github.com/docker/docker/pkg/sysinfo"
  28. "github.com/docker/docker/runconfig"
  29. "github.com/docker/docker/volume"
  30. "github.com/docker/libnetwork"
  31. nwconfig "github.com/docker/libnetwork/config"
  32. "github.com/docker/libnetwork/drivers/bridge"
  33. "github.com/docker/libnetwork/netlabel"
  34. "github.com/docker/libnetwork/netutils"
  35. "github.com/docker/libnetwork/options"
  36. lntypes "github.com/docker/libnetwork/types"
  37. "github.com/golang/protobuf/ptypes"
  38. "github.com/opencontainers/runc/libcontainer/cgroups"
  39. rsystem "github.com/opencontainers/runc/libcontainer/system"
  40. specs "github.com/opencontainers/runtime-spec/specs-go"
  41. "github.com/opencontainers/selinux/go-selinux/label"
  42. "github.com/pkg/errors"
  43. "github.com/sirupsen/logrus"
  44. "github.com/vishvananda/netlink"
  45. "golang.org/x/sys/unix"
  46. )
  47. const (
  48. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  49. linuxMinCPUShares = 2
  50. linuxMaxCPUShares = 262144
  51. platformSupported = true
  52. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  53. linuxMinMemory = 4194304
  54. // constants for remapped root settings
  55. defaultIDSpecifier string = "default"
  56. defaultRemappedID string = "dockremap"
  57. // constant for cgroup drivers
  58. cgroupFsDriver = "cgroupfs"
  59. cgroupSystemdDriver = "systemd"
  60. )
  61. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  62. memory := specs.LinuxMemory{}
  63. if config.Memory > 0 {
  64. memory.Limit = &config.Memory
  65. }
  66. if config.MemoryReservation > 0 {
  67. memory.Reservation = &config.MemoryReservation
  68. }
  69. if config.MemorySwap > 0 {
  70. memory.Swap = &config.MemorySwap
  71. }
  72. if config.MemorySwappiness != nil {
  73. swappiness := uint64(*config.MemorySwappiness)
  74. memory.Swappiness = &swappiness
  75. }
  76. if config.KernelMemory != 0 {
  77. memory.Kernel = &config.KernelMemory
  78. }
  79. return &memory
  80. }
  81. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  82. cpu := specs.LinuxCPU{}
  83. if config.CPUShares < 0 {
  84. return nil, fmt.Errorf("shares: invalid argument")
  85. }
  86. if config.CPUShares >= 0 {
  87. shares := uint64(config.CPUShares)
  88. cpu.Shares = &shares
  89. }
  90. if config.CpusetCpus != "" {
  91. cpu.Cpus = config.CpusetCpus
  92. }
  93. if config.CpusetMems != "" {
  94. cpu.Mems = config.CpusetMems
  95. }
  96. if config.NanoCPUs > 0 {
  97. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  98. period := uint64(100 * time.Millisecond / time.Microsecond)
  99. quota := config.NanoCPUs * int64(period) / 1e9
  100. cpu.Period = &period
  101. cpu.Quota = &quota
  102. }
  103. if config.CPUPeriod != 0 {
  104. period := uint64(config.CPUPeriod)
  105. cpu.Period = &period
  106. }
  107. if config.CPUQuota != 0 {
  108. q := config.CPUQuota
  109. cpu.Quota = &q
  110. }
  111. if config.CPURealtimePeriod != 0 {
  112. period := uint64(config.CPURealtimePeriod)
  113. cpu.RealtimePeriod = &period
  114. }
  115. if config.CPURealtimeRuntime != 0 {
  116. c := config.CPURealtimeRuntime
  117. cpu.RealtimeRuntime = &c
  118. }
  119. return &cpu, nil
  120. }
  121. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  122. var stat unix.Stat_t
  123. var blkioWeightDevices []specs.LinuxWeightDevice
  124. for _, weightDevice := range config.BlkioWeightDevice {
  125. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  126. return nil, err
  127. }
  128. weight := weightDevice.Weight
  129. d := specs.LinuxWeightDevice{Weight: &weight}
  130. d.Major = int64(stat.Rdev / 256)
  131. d.Minor = int64(stat.Rdev % 256)
  132. blkioWeightDevices = append(blkioWeightDevices, d)
  133. }
  134. return blkioWeightDevices, nil
  135. }
  136. func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfig *containertypes.HostConfig) error {
  137. container.NoNewPrivileges = daemon.configStore.NoNewPrivileges
  138. return parseSecurityOpt(container, hostConfig)
  139. }
  140. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  141. var (
  142. labelOpts []string
  143. err error
  144. )
  145. for _, opt := range config.SecurityOpt {
  146. if opt == "no-new-privileges" {
  147. container.NoNewPrivileges = true
  148. continue
  149. }
  150. if opt == "disable" {
  151. labelOpts = append(labelOpts, "disable")
  152. continue
  153. }
  154. var con []string
  155. if strings.Contains(opt, "=") {
  156. con = strings.SplitN(opt, "=", 2)
  157. } else if strings.Contains(opt, ":") {
  158. con = strings.SplitN(opt, ":", 2)
  159. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  160. }
  161. if len(con) != 2 {
  162. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  163. }
  164. switch con[0] {
  165. case "label":
  166. labelOpts = append(labelOpts, con[1])
  167. case "apparmor":
  168. container.AppArmorProfile = con[1]
  169. case "seccomp":
  170. container.SeccompProfile = con[1]
  171. case "no-new-privileges":
  172. noNewPrivileges, err := strconv.ParseBool(con[1])
  173. if err != nil {
  174. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  175. }
  176. container.NoNewPrivileges = noNewPrivileges
  177. default:
  178. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  179. }
  180. }
  181. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  182. return err
  183. }
  184. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.LinuxThrottleDevice, error) {
  185. var throttleDevices []specs.LinuxThrottleDevice
  186. var stat unix.Stat_t
  187. for _, d := range devs {
  188. if err := unix.Stat(d.Path, &stat); err != nil {
  189. return nil, err
  190. }
  191. d := specs.LinuxThrottleDevice{Rate: d.Rate}
  192. d.Major = int64(stat.Rdev / 256)
  193. d.Minor = int64(stat.Rdev % 256)
  194. throttleDevices = append(throttleDevices, d)
  195. }
  196. return throttleDevices, nil
  197. }
  198. func checkKernel() error {
  199. // Check for unsupported kernel versions
  200. // FIXME: it would be cleaner to not test for specific versions, but rather
  201. // test for specific functionalities.
  202. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  203. // without actually causing a kernel panic, so we need this workaround until
  204. // the circumstances of pre-3.10 crashes are clearer.
  205. // For details see https://github.com/docker/docker/issues/407
  206. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  207. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  208. if !kernel.CheckKernelVersion(3, 10, 0) {
  209. v, _ := kernel.GetKernelVersion()
  210. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  211. 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())
  212. }
  213. }
  214. return nil
  215. }
  216. // adaptContainerSettings is called during container creation to modify any
  217. // settings necessary in the HostConfig structure.
  218. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  219. if adjustCPUShares && hostConfig.CPUShares > 0 {
  220. // Handle unsupported CPUShares
  221. if hostConfig.CPUShares < linuxMinCPUShares {
  222. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  223. hostConfig.CPUShares = linuxMinCPUShares
  224. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  225. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  226. hostConfig.CPUShares = linuxMaxCPUShares
  227. }
  228. }
  229. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  230. // By default, MemorySwap is set to twice the size of Memory.
  231. hostConfig.MemorySwap = hostConfig.Memory * 2
  232. }
  233. if hostConfig.ShmSize == 0 {
  234. hostConfig.ShmSize = config.DefaultShmSize
  235. if daemon.configStore != nil {
  236. hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
  237. }
  238. }
  239. // Set default IPC mode, if unset for container
  240. if hostConfig.IpcMode.IsEmpty() {
  241. m := config.DefaultIpcMode
  242. if daemon.configStore != nil {
  243. m = daemon.configStore.IpcMode
  244. }
  245. hostConfig.IpcMode = containertypes.IpcMode(m)
  246. }
  247. var err error
  248. opts, err := daemon.generateSecurityOpt(hostConfig)
  249. if err != nil {
  250. return err
  251. }
  252. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, opts...)
  253. if hostConfig.OomKillDisable == nil {
  254. defaultOomKillDisable := false
  255. hostConfig.OomKillDisable = &defaultOomKillDisable
  256. }
  257. return nil
  258. }
  259. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  260. warnings := []string{}
  261. fixMemorySwappiness(resources)
  262. // memory subsystem checks and adjustments
  263. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  264. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  265. }
  266. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  267. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  268. logrus.Warn("Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  269. resources.Memory = 0
  270. resources.MemorySwap = -1
  271. }
  272. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  273. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  274. logrus.Warn("Your kernel does not support swap limit capabilities,or the cgroup is not mounted. Memory limited without swap.")
  275. resources.MemorySwap = -1
  276. }
  277. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  278. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  279. }
  280. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  281. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  282. }
  283. if resources.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
  284. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  285. logrus.Warn("Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.")
  286. resources.MemorySwappiness = nil
  287. }
  288. if resources.MemorySwappiness != nil {
  289. swappiness := *resources.MemorySwappiness
  290. if swappiness < 0 || swappiness > 100 {
  291. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  292. }
  293. }
  294. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  295. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  296. logrus.Warn("Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  297. resources.MemoryReservation = 0
  298. }
  299. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  300. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  301. }
  302. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  303. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  304. }
  305. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  306. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  307. logrus.Warn("Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  308. resources.KernelMemory = 0
  309. }
  310. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  311. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  312. }
  313. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  314. 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.")
  315. logrus.Warn("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.")
  316. }
  317. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  318. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  319. // warning the caller if they already wanted the feature to be off
  320. if *resources.OomKillDisable {
  321. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  322. logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  323. }
  324. resources.OomKillDisable = nil
  325. }
  326. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  327. warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  328. logrus.Warn("Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  329. resources.PidsLimit = 0
  330. }
  331. // cpu subsystem checks and adjustments
  332. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  333. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  334. }
  335. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  336. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  337. }
  338. if resources.NanoCPUs > 0 && (!sysInfo.CPUCfsPeriod || !sysInfo.CPUCfsQuota) {
  339. 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")
  340. }
  341. // The highest precision we could get on Linux is 0.001, by setting
  342. // cpu.cfs_period_us=1000ms
  343. // cpu.cfs_quota=1ms
  344. // See the following link for details:
  345. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  346. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  347. // The error message is 0.01 so that this is consistent with Windows
  348. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  349. 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())
  350. }
  351. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  352. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  353. logrus.Warn("Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  354. resources.CPUShares = 0
  355. }
  356. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  357. warnings = append(warnings, "Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  358. logrus.Warn("Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  359. resources.CPUPeriod = 0
  360. }
  361. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  362. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  363. }
  364. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  365. warnings = append(warnings, "Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  366. logrus.Warn("Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  367. resources.CPUQuota = 0
  368. }
  369. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  370. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  371. }
  372. if resources.CPUPercent > 0 {
  373. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  374. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  375. resources.CPUPercent = 0
  376. }
  377. // cpuset subsystem checks and adjustments
  378. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  379. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  380. logrus.Warn("Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  381. resources.CpusetCpus = ""
  382. resources.CpusetMems = ""
  383. }
  384. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  385. if err != nil {
  386. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  387. }
  388. if !cpusAvailable {
  389. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  390. }
  391. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  392. if err != nil {
  393. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  394. }
  395. if !memsAvailable {
  396. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  397. }
  398. // blkio subsystem checks and adjustments
  399. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  400. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  401. logrus.Warn("Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  402. resources.BlkioWeight = 0
  403. }
  404. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  405. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  406. }
  407. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  408. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  409. }
  410. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  411. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  412. logrus.Warn("Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  413. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  414. }
  415. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  416. 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.")
  417. logrus.Warn("Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded")
  418. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  419. }
  420. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  421. 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.")
  422. logrus.Warn("Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  423. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  424. }
  425. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  426. 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.")
  427. logrus.Warn("Your kernel does not support IOPS Block I/O read limit in IO or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  428. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  429. }
  430. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  431. 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.")
  432. logrus.Warn("Your kernel does not support IOPS Block I/O write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  433. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  434. }
  435. return warnings, nil
  436. }
  437. func (daemon *Daemon) getCgroupDriver() string {
  438. cgroupDriver := cgroupFsDriver
  439. if UsingSystemd(daemon.configStore) {
  440. cgroupDriver = cgroupSystemdDriver
  441. }
  442. return cgroupDriver
  443. }
  444. // getCD gets the raw value of the native.cgroupdriver option, if set.
  445. func getCD(config *config.Config) string {
  446. for _, option := range config.ExecOptions {
  447. key, val, err := parsers.ParseKeyValueOpt(option)
  448. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  449. continue
  450. }
  451. return val
  452. }
  453. return ""
  454. }
  455. // VerifyCgroupDriver validates native.cgroupdriver
  456. func VerifyCgroupDriver(config *config.Config) error {
  457. cd := getCD(config)
  458. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  459. return nil
  460. }
  461. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  462. }
  463. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  464. func UsingSystemd(config *config.Config) bool {
  465. return getCD(config) == cgroupSystemdDriver
  466. }
  467. // verifyPlatformContainerSettings performs platform-specific validation of the
  468. // hostconfig and config structures.
  469. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  470. var warnings []string
  471. sysInfo := sysinfo.New(true)
  472. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  473. if err != nil {
  474. return warnings, err
  475. }
  476. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  477. // no matter err is nil or not, w could have data in itself.
  478. warnings = append(warnings, w...)
  479. if err != nil {
  480. return warnings, err
  481. }
  482. if hostConfig.ShmSize < 0 {
  483. return warnings, fmt.Errorf("SHM size can not be less than 0")
  484. }
  485. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  486. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  487. }
  488. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  489. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  490. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  491. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  492. }
  493. // check for various conflicting options with user namespaces
  494. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  495. if hostConfig.Privileged {
  496. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  497. }
  498. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  499. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  500. }
  501. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  502. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  503. }
  504. }
  505. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  506. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  507. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  508. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  509. }
  510. }
  511. if hostConfig.Runtime == "" {
  512. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  513. }
  514. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  515. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  516. }
  517. for dest := range hostConfig.Tmpfs {
  518. if err := volume.ValidateTmpfsMountDestination(dest); err != nil {
  519. return warnings, err
  520. }
  521. }
  522. return warnings, nil
  523. }
  524. // reloadPlatform updates configuration with platform specific options
  525. // and updates the passed attributes
  526. func (daemon *Daemon) reloadPlatform(conf *config.Config, attributes map[string]string) error {
  527. if err := conf.ValidatePlatformConfig(); err != nil {
  528. return err
  529. }
  530. if conf.IsValueSet("runtimes") {
  531. daemon.configStore.Runtimes = conf.Runtimes
  532. // Always set the default one
  533. daemon.configStore.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  534. }
  535. if conf.DefaultRuntime != "" {
  536. daemon.configStore.DefaultRuntime = conf.DefaultRuntime
  537. }
  538. if conf.IsValueSet("default-shm-size") {
  539. daemon.configStore.ShmSize = conf.ShmSize
  540. }
  541. if conf.IpcMode != "" {
  542. daemon.configStore.IpcMode = conf.IpcMode
  543. }
  544. // Update attributes
  545. var runtimeList bytes.Buffer
  546. for name, rt := range daemon.configStore.Runtimes {
  547. if runtimeList.Len() > 0 {
  548. runtimeList.WriteRune(' ')
  549. }
  550. runtimeList.WriteString(fmt.Sprintf("%s:%s", name, rt))
  551. }
  552. attributes["runtimes"] = runtimeList.String()
  553. attributes["default-runtime"] = daemon.configStore.DefaultRuntime
  554. attributes["default-shm-size"] = fmt.Sprintf("%d", daemon.configStore.ShmSize)
  555. attributes["default-ipc-mode"] = daemon.configStore.IpcMode
  556. return nil
  557. }
  558. // verifyDaemonSettings performs validation of daemon config struct
  559. func verifyDaemonSettings(conf *config.Config) error {
  560. // Check for mutually incompatible config options
  561. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  562. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  563. }
  564. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  565. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  566. }
  567. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  568. conf.BridgeConfig.EnableIPMasq = false
  569. }
  570. if err := VerifyCgroupDriver(conf); err != nil {
  571. return err
  572. }
  573. if conf.CgroupParent != "" && UsingSystemd(conf) {
  574. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  575. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  576. }
  577. }
  578. if conf.DefaultRuntime == "" {
  579. conf.DefaultRuntime = config.StockRuntimeName
  580. }
  581. if conf.Runtimes == nil {
  582. conf.Runtimes = make(map[string]types.Runtime)
  583. }
  584. conf.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  585. return nil
  586. }
  587. // checkSystem validates platform-specific requirements
  588. func checkSystem() error {
  589. if os.Geteuid() != 0 {
  590. return fmt.Errorf("The Docker daemon needs to be run as root")
  591. }
  592. return checkKernel()
  593. }
  594. // configureMaxThreads sets the Go runtime max threads threshold
  595. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  596. func configureMaxThreads(config *config.Config) error {
  597. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  598. if err != nil {
  599. return err
  600. }
  601. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  602. if err != nil {
  603. return err
  604. }
  605. maxThreads := (mtint / 100) * 90
  606. debug.SetMaxThreads(maxThreads)
  607. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  608. return nil
  609. }
  610. func overlaySupportsSelinux() (bool, error) {
  611. f, err := os.Open("/proc/kallsyms")
  612. if err != nil {
  613. if os.IsNotExist(err) {
  614. return false, nil
  615. }
  616. return false, err
  617. }
  618. defer f.Close()
  619. var symAddr, symType, symName, text string
  620. s := bufio.NewScanner(f)
  621. for s.Scan() {
  622. if err := s.Err(); err != nil {
  623. return false, err
  624. }
  625. text = s.Text()
  626. if _, err := fmt.Sscanf(text, "%s %s %s", &symAddr, &symType, &symName); err != nil {
  627. return false, fmt.Errorf("Scanning '%s' failed: %s", text, err)
  628. }
  629. // Check for presence of symbol security_inode_copy_up.
  630. if symName == "security_inode_copy_up" {
  631. return true, nil
  632. }
  633. }
  634. return false, nil
  635. }
  636. // configureKernelSecuritySupport configures and validates security support for the kernel
  637. func configureKernelSecuritySupport(config *config.Config, driverNames []string) error {
  638. if config.EnableSelinuxSupport {
  639. if !selinuxEnabled() {
  640. logrus.Warn("Docker could not enable SELinux on the host system")
  641. return nil
  642. }
  643. overlayFound := false
  644. for _, d := range driverNames {
  645. if d == "overlay" || d == "overlay2" {
  646. overlayFound = true
  647. break
  648. }
  649. }
  650. if overlayFound {
  651. // If driver is overlay or overlay2, make sure kernel
  652. // supports selinux with overlay.
  653. supported, err := overlaySupportsSelinux()
  654. if err != nil {
  655. return err
  656. }
  657. if !supported {
  658. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverNames)
  659. }
  660. }
  661. } else {
  662. selinuxSetDisabled()
  663. }
  664. return nil
  665. }
  666. func (daemon *Daemon) initNetworkController(config *config.Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  667. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  668. if err != nil {
  669. return nil, err
  670. }
  671. controller, err := libnetwork.New(netOptions...)
  672. if err != nil {
  673. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  674. }
  675. if len(activeSandboxes) > 0 {
  676. logrus.Info("There are old running containers, the network config will not take affect")
  677. return controller, nil
  678. }
  679. // Initialize default network on "null"
  680. if n, _ := controller.NetworkByName("none"); n == nil {
  681. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  682. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  683. }
  684. }
  685. // Initialize default network on "host"
  686. if n, _ := controller.NetworkByName("host"); n == nil {
  687. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  688. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  689. }
  690. }
  691. // Clear stale bridge network
  692. if n, err := controller.NetworkByName("bridge"); err == nil {
  693. if err = n.Delete(); err != nil {
  694. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  695. }
  696. }
  697. if !config.DisableBridge {
  698. // Initialize default driver "bridge"
  699. if err := initBridgeDriver(controller, config); err != nil {
  700. return nil, err
  701. }
  702. } else {
  703. removeDefaultBridgeInterface()
  704. }
  705. return controller, nil
  706. }
  707. func driverOptions(config *config.Config) []nwconfig.Option {
  708. bridgeConfig := options.Generic{
  709. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  710. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  711. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  712. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath}
  713. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  714. dOptions := []nwconfig.Option{}
  715. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  716. return dOptions
  717. }
  718. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  719. bridgeName := bridge.DefaultBridgeName
  720. if config.BridgeConfig.Iface != "" {
  721. bridgeName = config.BridgeConfig.Iface
  722. }
  723. netOption := map[string]string{
  724. bridge.BridgeName: bridgeName,
  725. bridge.DefaultBridge: strconv.FormatBool(true),
  726. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  727. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  728. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  729. }
  730. // --ip processing
  731. if config.BridgeConfig.DefaultIP != nil {
  732. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  733. }
  734. var (
  735. ipamV4Conf *libnetwork.IpamConf
  736. ipamV6Conf *libnetwork.IpamConf
  737. )
  738. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  739. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  740. if err != nil {
  741. return errors.Wrap(err, "list bridge addresses failed")
  742. }
  743. nw := nwList[0]
  744. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  745. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  746. if err != nil {
  747. return errors.Wrap(err, "parse CIDR failed")
  748. }
  749. // Iterate through in case there are multiple addresses for the bridge
  750. for _, entry := range nwList {
  751. if fCIDR.Contains(entry.IP) {
  752. nw = entry
  753. break
  754. }
  755. }
  756. }
  757. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  758. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  759. if hip.IsGlobalUnicast() {
  760. ipamV4Conf.Gateway = nw.IP.String()
  761. }
  762. if config.BridgeConfig.IP != "" {
  763. ipamV4Conf.PreferredPool = config.BridgeConfig.IP
  764. ip, _, err := net.ParseCIDR(config.BridgeConfig.IP)
  765. if err != nil {
  766. return err
  767. }
  768. ipamV4Conf.Gateway = ip.String()
  769. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  770. 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)
  771. }
  772. if config.BridgeConfig.FixedCIDR != "" {
  773. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  774. if err != nil {
  775. return err
  776. }
  777. ipamV4Conf.SubPool = fCIDR.String()
  778. }
  779. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  780. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  781. }
  782. var deferIPv6Alloc bool
  783. if config.BridgeConfig.FixedCIDRv6 != "" {
  784. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  785. if err != nil {
  786. return err
  787. }
  788. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  789. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  790. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  791. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  792. // on this network until after the driver has created the endpoint and returned the
  793. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  794. ones, _ := fCIDRv6.Mask.Size()
  795. deferIPv6Alloc = ones <= 80
  796. if ipamV6Conf == nil {
  797. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  798. }
  799. ipamV6Conf.PreferredPool = fCIDRv6.String()
  800. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  801. // address belongs to the same network, we need to inform libnetwork about it, so
  802. // that it can be reserved with IPAM and it will not be given away to somebody else
  803. for _, nw6 := range nw6List {
  804. if fCIDRv6.Contains(nw6.IP) {
  805. ipamV6Conf.Gateway = nw6.IP.String()
  806. break
  807. }
  808. }
  809. }
  810. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  811. if ipamV6Conf == nil {
  812. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  813. }
  814. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  815. }
  816. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  817. v6Conf := []*libnetwork.IpamConf{}
  818. if ipamV6Conf != nil {
  819. v6Conf = append(v6Conf, ipamV6Conf)
  820. }
  821. // Initialize default network on "bridge" with the same name
  822. _, err = controller.NewNetwork("bridge", "bridge", "",
  823. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  824. libnetwork.NetworkOptionDriverOpts(netOption),
  825. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  826. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  827. if err != nil {
  828. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  829. }
  830. return nil
  831. }
  832. // Remove default bridge interface if present (--bridge=none use case)
  833. func removeDefaultBridgeInterface() {
  834. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  835. if err := netlink.LinkDel(lnk); err != nil {
  836. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  837. }
  838. }
  839. }
  840. func (daemon *Daemon) getLayerInit() func(string) error {
  841. return daemon.setupInitLayer
  842. }
  843. // Parse the remapped root (user namespace) option, which can be one of:
  844. // username - valid username from /etc/passwd
  845. // username:groupname - valid username; valid groupname from /etc/group
  846. // uid - 32-bit unsigned int valid Linux UID value
  847. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  848. //
  849. // If no groupname is specified, and a username is specified, an attempt
  850. // will be made to lookup a gid for that username as a groupname
  851. //
  852. // If names are used, they are verified to exist in passwd/group
  853. func parseRemappedRoot(usergrp string) (string, string, error) {
  854. var (
  855. userID, groupID int
  856. username, groupname string
  857. )
  858. idparts := strings.Split(usergrp, ":")
  859. if len(idparts) > 2 {
  860. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  861. }
  862. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  863. // must be a uid; take it as valid
  864. userID = int(uid)
  865. luser, err := idtools.LookupUID(userID)
  866. if err != nil {
  867. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  868. }
  869. username = luser.Name
  870. if len(idparts) == 1 {
  871. // if the uid was numeric and no gid was specified, take the uid as the gid
  872. groupID = userID
  873. lgrp, err := idtools.LookupGID(groupID)
  874. if err != nil {
  875. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  876. }
  877. groupname = lgrp.Name
  878. }
  879. } else {
  880. lookupName := idparts[0]
  881. // special case: if the user specified "default", they want Docker to create or
  882. // use (after creation) the "dockremap" user/group for root remapping
  883. if lookupName == defaultIDSpecifier {
  884. lookupName = defaultRemappedID
  885. }
  886. luser, err := idtools.LookupUser(lookupName)
  887. if err != nil && idparts[0] != defaultIDSpecifier {
  888. // error if the name requested isn't the special "dockremap" ID
  889. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  890. } else if err != nil {
  891. // special case-- if the username == "default", then we have been asked
  892. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  893. // ranges will be used for the user and group mappings in user namespaced containers
  894. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  895. if err == nil {
  896. return defaultRemappedID, defaultRemappedID, nil
  897. }
  898. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  899. }
  900. username = luser.Name
  901. if len(idparts) == 1 {
  902. // we only have a string username, and no group specified; look up gid from username as group
  903. group, err := idtools.LookupGroup(lookupName)
  904. if err != nil {
  905. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  906. }
  907. groupname = group.Name
  908. }
  909. }
  910. if len(idparts) == 2 {
  911. // groupname or gid is separately specified and must be resolved
  912. // to an unsigned 32-bit gid
  913. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  914. // must be a gid, take it as valid
  915. groupID = int(gid)
  916. lgrp, err := idtools.LookupGID(groupID)
  917. if err != nil {
  918. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  919. }
  920. groupname = lgrp.Name
  921. } else {
  922. // not a number; attempt a lookup
  923. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  924. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  925. }
  926. groupname = idparts[1]
  927. }
  928. }
  929. return username, groupname, nil
  930. }
  931. func setupRemappedRoot(config *config.Config) (*idtools.IDMappings, error) {
  932. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  933. return nil, fmt.Errorf("User namespaces are only supported on Linux")
  934. }
  935. // if the daemon was started with remapped root option, parse
  936. // the config option to the int uid,gid values
  937. if config.RemappedRoot != "" {
  938. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  939. if err != nil {
  940. return nil, err
  941. }
  942. if username == "root" {
  943. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  944. // effectively
  945. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  946. return &idtools.IDMappings{}, nil
  947. }
  948. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  949. // update remapped root setting now that we have resolved them to actual names
  950. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  951. mappings, err := idtools.NewIDMappings(username, groupname)
  952. if err != nil {
  953. return nil, errors.Wrapf(err, "Can't create ID mappings: %v")
  954. }
  955. return mappings, nil
  956. }
  957. return &idtools.IDMappings{}, nil
  958. }
  959. func setupDaemonRoot(config *config.Config, rootDir string, rootIDs idtools.IDPair) error {
  960. config.Root = rootDir
  961. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  962. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  963. // (e.g. mounted layers of a container) can traverse this path.
  964. // The user namespace support will create subdirectories for the remapped root host uid:gid
  965. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  966. // layer content subtrees.
  967. if _, err := os.Stat(rootDir); err == nil {
  968. // root current exists; verify the access bits are correct by setting them
  969. if err = os.Chmod(rootDir, 0711); err != nil {
  970. return err
  971. }
  972. } else if os.IsNotExist(err) {
  973. // no root exists yet, create it 0711 with root:root ownership
  974. if err := os.MkdirAll(rootDir, 0711); err != nil {
  975. return err
  976. }
  977. }
  978. // if user namespaces are enabled we will create a subtree underneath the specified root
  979. // with any/all specified remapped root uid/gid options on the daemon creating
  980. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  981. // `chdir()` to work for containers namespaced to that uid/gid)
  982. if config.RemappedRoot != "" {
  983. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootIDs.UID, rootIDs.GID))
  984. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  985. // Create the root directory if it doesn't exist
  986. if err := idtools.MkdirAllAndChown(config.Root, 0700, rootIDs); err != nil {
  987. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  988. }
  989. // we also need to verify that any pre-existing directories in the path to
  990. // the graphroot won't block access to remapped root--if any pre-existing directory
  991. // has strict permissions that don't allow "x", container start will fail, so
  992. // better to warn and fail now
  993. dirPath := config.Root
  994. for {
  995. dirPath = filepath.Dir(dirPath)
  996. if dirPath == "/" {
  997. break
  998. }
  999. if !idtools.CanAccess(dirPath, rootIDs) {
  1000. 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)
  1001. }
  1002. }
  1003. }
  1004. return nil
  1005. }
  1006. // registerLinks writes the links to a file.
  1007. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1008. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1009. return nil
  1010. }
  1011. for _, l := range hostConfig.Links {
  1012. name, alias, err := opts.ParseLink(l)
  1013. if err != nil {
  1014. return err
  1015. }
  1016. child, err := daemon.GetContainer(name)
  1017. if err != nil {
  1018. return errors.Wrapf(err, "could not get container for %s", name)
  1019. }
  1020. for child.HostConfig.NetworkMode.IsContainer() {
  1021. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  1022. child, err = daemon.GetContainer(parts[1])
  1023. if err != nil {
  1024. return errors.Wrapf(err, "Could not get container for %s", parts[1])
  1025. }
  1026. }
  1027. if child.HostConfig.NetworkMode.IsHost() {
  1028. return runconfig.ErrConflictHostNetworkAndLinks
  1029. }
  1030. if err := daemon.registerLink(container, child, alias); err != nil {
  1031. return err
  1032. }
  1033. }
  1034. // After we load all the links into the daemon
  1035. // set them to nil on the hostconfig
  1036. _, err := container.WriteHostConfig()
  1037. return err
  1038. }
  1039. // conditionalMountOnStart is a platform specific helper function during the
  1040. // container start to call mount.
  1041. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1042. return daemon.Mount(container)
  1043. }
  1044. // conditionalUnmountOnCleanup is a platform specific helper function called
  1045. // during the cleanup of a container to unmount.
  1046. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1047. return daemon.Unmount(container)
  1048. }
  1049. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1050. if !c.IsRunning() {
  1051. return nil, errNotRunning(c.ID)
  1052. }
  1053. stats, err := daemon.containerd.Stats(c.ID)
  1054. if err != nil {
  1055. if strings.Contains(err.Error(), "container not found") {
  1056. return nil, containerNotFound(c.ID)
  1057. }
  1058. return nil, err
  1059. }
  1060. s := &types.StatsJSON{}
  1061. cgs := stats.CgroupStats
  1062. if cgs != nil {
  1063. s.BlkioStats = types.BlkioStats{
  1064. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  1065. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  1066. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  1067. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  1068. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  1069. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  1070. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  1071. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  1072. }
  1073. cpu := cgs.CpuStats
  1074. s.CPUStats = types.CPUStats{
  1075. CPUUsage: types.CPUUsage{
  1076. TotalUsage: cpu.CpuUsage.TotalUsage,
  1077. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  1078. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  1079. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  1080. },
  1081. ThrottlingData: types.ThrottlingData{
  1082. Periods: cpu.ThrottlingData.Periods,
  1083. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  1084. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  1085. },
  1086. }
  1087. mem := cgs.MemoryStats.Usage
  1088. s.MemoryStats = types.MemoryStats{
  1089. Usage: mem.Usage,
  1090. MaxUsage: mem.MaxUsage,
  1091. Stats: cgs.MemoryStats.Stats,
  1092. Failcnt: mem.Failcnt,
  1093. Limit: mem.Limit,
  1094. }
  1095. // if the container does not set memory limit, use the machineMemory
  1096. if mem.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1097. s.MemoryStats.Limit = daemon.machineMemory
  1098. }
  1099. if cgs.PidsStats != nil {
  1100. s.PidsStats = types.PidsStats{
  1101. Current: cgs.PidsStats.Current,
  1102. }
  1103. }
  1104. }
  1105. s.Read, err = ptypes.Timestamp(stats.Timestamp)
  1106. if err != nil {
  1107. return nil, err
  1108. }
  1109. return s, nil
  1110. }
  1111. // setDefaultIsolation determines the default isolation mode for the
  1112. // daemon to run in. This is only applicable on Windows
  1113. func (daemon *Daemon) setDefaultIsolation() error {
  1114. return nil
  1115. }
  1116. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1117. var layers []string
  1118. for _, l := range rootfs.DiffIDs {
  1119. layers = append(layers, l.String())
  1120. }
  1121. return types.RootFS{
  1122. Type: rootfs.Type,
  1123. Layers: layers,
  1124. }
  1125. }
  1126. // setupDaemonProcess sets various settings for the daemon's process
  1127. func setupDaemonProcess(config *config.Config) error {
  1128. // setup the daemons oom_score_adj
  1129. return setupOOMScoreAdj(config.OOMScoreAdjust)
  1130. }
  1131. func setupOOMScoreAdj(score int) error {
  1132. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1133. if err != nil {
  1134. return err
  1135. }
  1136. defer f.Close()
  1137. stringScore := strconv.Itoa(score)
  1138. _, err = f.WriteString(stringScore)
  1139. if os.IsPermission(err) {
  1140. // Setting oom_score_adj does not work in an
  1141. // unprivileged container. Ignore the error, but log
  1142. // it if we appear not to be in that situation.
  1143. if !rsystem.RunningInUserNS() {
  1144. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1145. }
  1146. return nil
  1147. }
  1148. return err
  1149. }
  1150. func (daemon *Daemon) initCgroupsPath(path string) error {
  1151. if path == "/" || path == "." {
  1152. return nil
  1153. }
  1154. if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
  1155. return nil
  1156. }
  1157. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1158. // for the period and runtime as this limits what the children can be set to.
  1159. daemon.initCgroupsPath(filepath.Dir(path))
  1160. mnt, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
  1161. if err != nil {
  1162. return err
  1163. }
  1164. // When docker is run inside docker, the root is based of the host cgroup.
  1165. // Should this be handled in runc/libcontainer/cgroups ?
  1166. if strings.HasPrefix(root, "/docker/") {
  1167. root = "/"
  1168. }
  1169. path = filepath.Join(mnt, root, path)
  1170. sysinfo := sysinfo.New(true)
  1171. if err := maybeCreateCPURealTimeFile(sysinfo.CPURealtimePeriod, daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1172. return err
  1173. }
  1174. if err := maybeCreateCPURealTimeFile(sysinfo.CPURealtimeRuntime, daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path); err != nil {
  1175. return err
  1176. }
  1177. return nil
  1178. }
  1179. func maybeCreateCPURealTimeFile(sysinfoPresent bool, configValue int64, file string, path string) error {
  1180. if sysinfoPresent && configValue != 0 {
  1181. if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
  1182. return err
  1183. }
  1184. if err := ioutil.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700); err != nil {
  1185. return err
  1186. }
  1187. }
  1188. return nil
  1189. }
  1190. func (daemon *Daemon) setupSeccompProfile() error {
  1191. if daemon.configStore.SeccompProfile != "" {
  1192. daemon.seccompProfilePath = daemon.configStore.SeccompProfile
  1193. b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
  1194. if err != nil {
  1195. return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
  1196. }
  1197. daemon.seccompProfile = b
  1198. }
  1199. return nil
  1200. }