daemon_unix.go 48 KB

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