daemon_unix.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "runtime/debug"
  11. "strconv"
  12. "strings"
  13. "syscall"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/container"
  16. derr "github.com/docker/docker/errors"
  17. "github.com/docker/docker/image"
  18. "github.com/docker/docker/layer"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/parsers"
  21. "github.com/docker/docker/pkg/parsers/kernel"
  22. "github.com/docker/docker/pkg/sysinfo"
  23. "github.com/docker/docker/reference"
  24. "github.com/docker/docker/runconfig"
  25. runconfigopts "github.com/docker/docker/runconfig/opts"
  26. pblkiodev "github.com/docker/engine-api/types/blkiodev"
  27. containertypes "github.com/docker/engine-api/types/container"
  28. "github.com/docker/libnetwork"
  29. nwconfig "github.com/docker/libnetwork/config"
  30. "github.com/docker/libnetwork/drivers/bridge"
  31. "github.com/docker/libnetwork/ipamutils"
  32. "github.com/docker/libnetwork/netlabel"
  33. "github.com/docker/libnetwork/options"
  34. "github.com/docker/libnetwork/types"
  35. blkiodev "github.com/opencontainers/runc/libcontainer/configs"
  36. "github.com/opencontainers/runc/libcontainer/label"
  37. "github.com/opencontainers/runc/libcontainer/user"
  38. )
  39. const (
  40. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  41. linuxMinCPUShares = 2
  42. linuxMaxCPUShares = 262144
  43. platformSupported = true
  44. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  45. linuxMinMemory = 4194304
  46. // constants for remapped root settings
  47. defaultIDSpecifier string = "default"
  48. defaultRemappedID string = "dockremap"
  49. )
  50. func getBlkioWeightDevices(config *containertypes.HostConfig) ([]*blkiodev.WeightDevice, error) {
  51. var stat syscall.Stat_t
  52. var blkioWeightDevices []*blkiodev.WeightDevice
  53. for _, weightDevice := range config.BlkioWeightDevice {
  54. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  55. return nil, err
  56. }
  57. weightDevice := blkiodev.NewWeightDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), weightDevice.Weight, 0)
  58. blkioWeightDevices = append(blkioWeightDevices, weightDevice)
  59. }
  60. return blkioWeightDevices, nil
  61. }
  62. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  63. var (
  64. labelOpts []string
  65. err error
  66. )
  67. for _, opt := range config.SecurityOpt {
  68. con := strings.SplitN(opt, ":", 2)
  69. if len(con) == 1 {
  70. return fmt.Errorf("Invalid --security-opt: %q", opt)
  71. }
  72. switch con[0] {
  73. case "label":
  74. labelOpts = append(labelOpts, con[1])
  75. case "apparmor":
  76. container.AppArmorProfile = con[1]
  77. case "seccomp":
  78. container.SeccompProfile = con[1]
  79. default:
  80. return fmt.Errorf("Invalid --security-opt: %q", opt)
  81. }
  82. }
  83. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  84. return err
  85. }
  86. func getBlkioReadIOpsDevices(config *containertypes.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  87. var blkioReadIOpsDevice []*blkiodev.ThrottleDevice
  88. var stat syscall.Stat_t
  89. for _, iopsDevice := range config.BlkioDeviceReadIOps {
  90. if err := syscall.Stat(iopsDevice.Path, &stat); err != nil {
  91. return nil, err
  92. }
  93. readIOpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), iopsDevice.Rate)
  94. blkioReadIOpsDevice = append(blkioReadIOpsDevice, readIOpsDevice)
  95. }
  96. return blkioReadIOpsDevice, nil
  97. }
  98. func getBlkioWriteIOpsDevices(config *containertypes.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  99. var blkioWriteIOpsDevice []*blkiodev.ThrottleDevice
  100. var stat syscall.Stat_t
  101. for _, iopsDevice := range config.BlkioDeviceWriteIOps {
  102. if err := syscall.Stat(iopsDevice.Path, &stat); err != nil {
  103. return nil, err
  104. }
  105. writeIOpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), iopsDevice.Rate)
  106. blkioWriteIOpsDevice = append(blkioWriteIOpsDevice, writeIOpsDevice)
  107. }
  108. return blkioWriteIOpsDevice, nil
  109. }
  110. func getBlkioReadBpsDevices(config *containertypes.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  111. var blkioReadBpsDevice []*blkiodev.ThrottleDevice
  112. var stat syscall.Stat_t
  113. for _, bpsDevice := range config.BlkioDeviceReadBps {
  114. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  115. return nil, err
  116. }
  117. readBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  118. blkioReadBpsDevice = append(blkioReadBpsDevice, readBpsDevice)
  119. }
  120. return blkioReadBpsDevice, nil
  121. }
  122. func getBlkioWriteBpsDevices(config *containertypes.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  123. var blkioWriteBpsDevice []*blkiodev.ThrottleDevice
  124. var stat syscall.Stat_t
  125. for _, bpsDevice := range config.BlkioDeviceWriteBps {
  126. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  127. return nil, err
  128. }
  129. writeBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  130. blkioWriteBpsDevice = append(blkioWriteBpsDevice, writeBpsDevice)
  131. }
  132. return blkioWriteBpsDevice, nil
  133. }
  134. func checkKernelVersion(k, major, minor int) bool {
  135. if v, err := kernel.GetKernelVersion(); err != nil {
  136. logrus.Warnf("%s", err)
  137. } else {
  138. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  139. return false
  140. }
  141. }
  142. return true
  143. }
  144. func checkKernel() error {
  145. // Check for unsupported kernel versions
  146. // FIXME: it would be cleaner to not test for specific versions, but rather
  147. // test for specific functionalities.
  148. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  149. // without actually causing a kernel panic, so we need this workaround until
  150. // the circumstances of pre-3.10 crashes are clearer.
  151. // For details see https://github.com/docker/docker/issues/407
  152. if !checkKernelVersion(3, 10, 0) {
  153. v, _ := kernel.GetKernelVersion()
  154. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  155. logrus.Warnf("Your Linux kernel version %s can be unstable running docker. Please upgrade your kernel to 3.10.0.", v.String())
  156. }
  157. }
  158. return nil
  159. }
  160. // adaptContainerSettings is called during container creation to modify any
  161. // settings necessary in the HostConfig structure.
  162. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  163. if adjustCPUShares && hostConfig.CPUShares > 0 {
  164. // Handle unsupported CPUShares
  165. if hostConfig.CPUShares < linuxMinCPUShares {
  166. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  167. hostConfig.CPUShares = linuxMinCPUShares
  168. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  169. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  170. hostConfig.CPUShares = linuxMaxCPUShares
  171. }
  172. }
  173. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  174. // By default, MemorySwap is set to twice the size of Memory.
  175. hostConfig.MemorySwap = hostConfig.Memory * 2
  176. }
  177. if hostConfig.ShmSize == 0 {
  178. hostConfig.ShmSize = container.DefaultSHMSize
  179. }
  180. var err error
  181. if hostConfig.SecurityOpt == nil {
  182. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode)
  183. if err != nil {
  184. return err
  185. }
  186. }
  187. if hostConfig.MemorySwappiness == nil {
  188. defaultSwappiness := int64(-1)
  189. hostConfig.MemorySwappiness = &defaultSwappiness
  190. }
  191. if hostConfig.OomKillDisable == nil {
  192. defaultOomKillDisable := false
  193. hostConfig.OomKillDisable = &defaultOomKillDisable
  194. }
  195. return nil
  196. }
  197. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo) ([]string, error) {
  198. warnings := []string{}
  199. // memory subsystem checks and adjustments
  200. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  201. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  202. }
  203. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  204. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  205. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  206. resources.Memory = 0
  207. resources.MemorySwap = -1
  208. }
  209. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  210. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  211. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  212. resources.MemorySwap = -1
  213. }
  214. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  215. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  216. }
  217. if resources.Memory == 0 && resources.MemorySwap > 0 {
  218. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  219. }
  220. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  221. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  222. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  223. resources.MemorySwappiness = nil
  224. }
  225. if resources.MemorySwappiness != nil {
  226. swappiness := *resources.MemorySwappiness
  227. if swappiness < -1 || swappiness > 100 {
  228. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  229. }
  230. }
  231. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  232. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  233. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  234. resources.MemoryReservation = 0
  235. }
  236. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  237. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage.")
  238. }
  239. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  240. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  241. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  242. resources.KernelMemory = 0
  243. }
  244. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  245. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  246. }
  247. if resources.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  248. 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.")
  249. logrus.Warnf("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.")
  250. }
  251. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  252. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  253. // warning the caller if they already wanted the feature to be off
  254. if *resources.OomKillDisable {
  255. warnings = append(warnings, "Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  256. logrus.Warnf("Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  257. }
  258. resources.OomKillDisable = nil
  259. }
  260. // cpu subsystem checks and adjustments
  261. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  262. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  263. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  264. resources.CPUShares = 0
  265. }
  266. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  267. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  268. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  269. resources.CPUPeriod = 0
  270. }
  271. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  272. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  273. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  274. resources.CPUQuota = 0
  275. }
  276. // cpuset subsystem checks and adjustments
  277. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  278. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  279. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  280. resources.CpusetCpus = ""
  281. resources.CpusetMems = ""
  282. }
  283. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  284. if err != nil {
  285. return warnings, derr.ErrorCodeInvalidCpusetCpus.WithArgs(resources.CpusetCpus)
  286. }
  287. if !cpusAvailable {
  288. return warnings, derr.ErrorCodeNotAvailableCpusetCpus.WithArgs(resources.CpusetCpus, sysInfo.Cpus)
  289. }
  290. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  291. if err != nil {
  292. return warnings, derr.ErrorCodeInvalidCpusetMems.WithArgs(resources.CpusetMems)
  293. }
  294. if !memsAvailable {
  295. return warnings, derr.ErrorCodeNotAvailableCpusetMems.WithArgs(resources.CpusetMems, sysInfo.Mems)
  296. }
  297. // blkio subsystem checks and adjustments
  298. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  299. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  300. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  301. resources.BlkioWeight = 0
  302. }
  303. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  304. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  305. }
  306. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  307. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  308. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  309. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  310. }
  311. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  312. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  313. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  314. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  315. }
  316. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  317. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  318. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  319. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  320. }
  321. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  322. warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
  323. logrus.Warnf("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
  324. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  325. }
  326. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  327. warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
  328. logrus.Warnf("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
  329. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  330. }
  331. return warnings, nil
  332. }
  333. func usingSystemd(config *Config) bool {
  334. for _, option := range config.ExecOptions {
  335. key, val, err := parsers.ParseKeyValueOpt(option)
  336. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  337. continue
  338. }
  339. if val == "systemd" {
  340. return true
  341. }
  342. }
  343. return false
  344. }
  345. func (daemon *Daemon) usingSystemd() bool {
  346. return usingSystemd(daemon.configStore)
  347. }
  348. // verifyPlatformContainerSettings performs platform-specific validation of the
  349. // hostconfig and config structures.
  350. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config) ([]string, error) {
  351. warnings := []string{}
  352. sysInfo := sysinfo.New(true)
  353. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  354. if err != nil {
  355. return warnings, err
  356. }
  357. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo)
  358. if err != nil {
  359. return warnings, err
  360. }
  361. warnings = append(warnings, w...)
  362. if hostConfig.ShmSize < 0 {
  363. return warnings, fmt.Errorf("SHM size must be greater then 0")
  364. }
  365. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  366. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000].", hostConfig.OomScoreAdj)
  367. }
  368. if sysInfo.IPv4ForwardingDisabled {
  369. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  370. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  371. }
  372. // check for various conflicting options with user namespaces
  373. if daemon.configStore.RemappedRoot != "" {
  374. if hostConfig.Privileged {
  375. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  376. }
  377. if hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsContainer() {
  378. return warnings, fmt.Errorf("Cannot share the host or a container's network namespace when user namespaces are enabled")
  379. }
  380. if hostConfig.PidMode.IsHost() {
  381. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  382. }
  383. if hostConfig.IpcMode.IsContainer() {
  384. return warnings, fmt.Errorf("Cannot share a container's IPC namespace when user namespaces are enabled")
  385. }
  386. if hostConfig.ReadonlyRootfs {
  387. return warnings, fmt.Errorf("Cannot use the --read-only option when user namespaces are enabled")
  388. }
  389. }
  390. if hostConfig.CgroupParent != "" && daemon.usingSystemd() {
  391. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  392. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  393. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  394. }
  395. }
  396. return warnings, nil
  397. }
  398. // verifyDaemonSettings performs validation of daemon config struct
  399. func verifyDaemonSettings(config *Config) error {
  400. // Check for mutually incompatible config options
  401. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  402. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  403. }
  404. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  405. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  406. }
  407. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  408. config.bridgeConfig.EnableIPMasq = false
  409. }
  410. if config.CgroupParent != "" && usingSystemd(config) {
  411. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  412. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  413. }
  414. }
  415. return nil
  416. }
  417. // checkSystem validates platform-specific requirements
  418. func checkSystem() error {
  419. if os.Geteuid() != 0 {
  420. return fmt.Errorf("The Docker daemon needs to be run as root")
  421. }
  422. return checkKernel()
  423. }
  424. // configureMaxThreads sets the Go runtime max threads threshold
  425. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  426. func configureMaxThreads(config *Config) error {
  427. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  428. if err != nil {
  429. return err
  430. }
  431. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  432. if err != nil {
  433. return err
  434. }
  435. maxThreads := (mtint / 100) * 90
  436. debug.SetMaxThreads(maxThreads)
  437. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  438. return nil
  439. }
  440. // configureKernelSecuritySupport configures and validate security support for the kernel
  441. func configureKernelSecuritySupport(config *Config, driverName string) error {
  442. if config.EnableSelinuxSupport {
  443. if selinuxEnabled() {
  444. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  445. if driverName == "overlay" {
  446. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  447. }
  448. logrus.Debug("SELinux enabled successfully")
  449. } else {
  450. logrus.Warn("Docker could not enable SELinux on the host system")
  451. }
  452. } else {
  453. selinuxSetDisabled()
  454. }
  455. return nil
  456. }
  457. func isBridgeNetworkDisabled(config *Config) bool {
  458. return config.bridgeConfig.Iface == disableNetworkBridge
  459. }
  460. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  461. options := []nwconfig.Option{}
  462. if dconfig == nil {
  463. return options, nil
  464. }
  465. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  466. dd := runconfig.DefaultDaemonNetworkMode()
  467. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  468. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  469. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  470. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  471. kv := strings.Split(dconfig.ClusterStore, "://")
  472. if len(kv) != 2 {
  473. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  474. }
  475. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  476. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  477. }
  478. if len(dconfig.ClusterOpts) > 0 {
  479. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  480. }
  481. if daemon.discoveryWatcher != nil {
  482. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  483. }
  484. if dconfig.ClusterAdvertise != "" {
  485. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  486. }
  487. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  488. options = append(options, driverOptions(dconfig)...)
  489. return options, nil
  490. }
  491. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  492. netOptions, err := daemon.networkOptions(config)
  493. if err != nil {
  494. return nil, err
  495. }
  496. controller, err := libnetwork.New(netOptions...)
  497. if err != nil {
  498. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  499. }
  500. // Initialize default network on "null"
  501. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  502. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  503. }
  504. // Initialize default network on "host"
  505. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  506. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  507. }
  508. if !config.DisableBridge {
  509. // Initialize default driver "bridge"
  510. if err := initBridgeDriver(controller, config); err != nil {
  511. return nil, err
  512. }
  513. }
  514. return controller, nil
  515. }
  516. func driverOptions(config *Config) []nwconfig.Option {
  517. bridgeConfig := options.Generic{
  518. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  519. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  520. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy}
  521. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  522. dOptions := []nwconfig.Option{}
  523. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  524. return dOptions
  525. }
  526. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  527. if n, err := controller.NetworkByName("bridge"); err == nil {
  528. if err = n.Delete(); err != nil {
  529. return fmt.Errorf("could not delete the default bridge network: %v", err)
  530. }
  531. }
  532. bridgeName := bridge.DefaultBridgeName
  533. if config.bridgeConfig.Iface != "" {
  534. bridgeName = config.bridgeConfig.Iface
  535. }
  536. netOption := map[string]string{
  537. bridge.BridgeName: bridgeName,
  538. bridge.DefaultBridge: strconv.FormatBool(true),
  539. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  540. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  541. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  542. }
  543. // --ip processing
  544. if config.bridgeConfig.DefaultIP != nil {
  545. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  546. }
  547. var (
  548. ipamV4Conf *libnetwork.IpamConf
  549. ipamV6Conf *libnetwork.IpamConf
  550. )
  551. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  552. nw, nw6List, err := ipamutils.ElectInterfaceAddresses(bridgeName)
  553. if err == nil {
  554. ipamV4Conf.PreferredPool = types.GetIPNetCanonical(nw).String()
  555. hip, _ := types.GetHostPartIP(nw.IP, nw.Mask)
  556. if hip.IsGlobalUnicast() {
  557. ipamV4Conf.Gateway = nw.IP.String()
  558. }
  559. }
  560. if config.bridgeConfig.IP != "" {
  561. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  562. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  563. if err != nil {
  564. return err
  565. }
  566. ipamV4Conf.Gateway = ip.String()
  567. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  568. 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)
  569. }
  570. if config.bridgeConfig.FixedCIDR != "" {
  571. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  572. if err != nil {
  573. return err
  574. }
  575. ipamV4Conf.SubPool = fCIDR.String()
  576. }
  577. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  578. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  579. }
  580. var deferIPv6Alloc bool
  581. if config.bridgeConfig.FixedCIDRv6 != "" {
  582. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  583. if err != nil {
  584. return err
  585. }
  586. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  587. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  588. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  589. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  590. // on this network until after the driver has created the endpoint and returned the
  591. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  592. ones, _ := fCIDRv6.Mask.Size()
  593. deferIPv6Alloc = ones <= 80
  594. if ipamV6Conf == nil {
  595. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  596. }
  597. ipamV6Conf.PreferredPool = fCIDRv6.String()
  598. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  599. // address belongs to the same network, we need to inform libnetwork about it, so
  600. // that it can be reserved with IPAM and it will not be given away to somebody else
  601. for _, nw6 := range nw6List {
  602. if fCIDRv6.Contains(nw6.IP) {
  603. ipamV6Conf.Gateway = nw6.IP.String()
  604. break
  605. }
  606. }
  607. }
  608. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  609. if ipamV6Conf == nil {
  610. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  611. }
  612. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  613. }
  614. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  615. v6Conf := []*libnetwork.IpamConf{}
  616. if ipamV6Conf != nil {
  617. v6Conf = append(v6Conf, ipamV6Conf)
  618. }
  619. // Initialize default network on "bridge" with the same name
  620. _, err = controller.NewNetwork("bridge", "bridge",
  621. libnetwork.NetworkOptionGeneric(options.Generic{
  622. netlabel.GenericData: netOption,
  623. netlabel.EnableIPv6: config.bridgeConfig.EnableIPv6,
  624. }),
  625. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  626. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  627. if err != nil {
  628. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  629. }
  630. return nil
  631. }
  632. // setupInitLayer populates a directory with mountpoints suitable
  633. // for bind-mounting things into the container.
  634. //
  635. // This extra layer is used by all containers as the top-most ro layer. It protects
  636. // the container from unwanted side-effects on the rw layer.
  637. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  638. for pth, typ := range map[string]string{
  639. "/dev/pts": "dir",
  640. "/dev/shm": "dir",
  641. "/proc": "dir",
  642. "/sys": "dir",
  643. "/.dockerenv": "file",
  644. "/etc/resolv.conf": "file",
  645. "/etc/hosts": "file",
  646. "/etc/hostname": "file",
  647. "/dev/console": "file",
  648. "/etc/mtab": "/proc/mounts",
  649. } {
  650. parts := strings.Split(pth, "/")
  651. prev := "/"
  652. for _, p := range parts[1:] {
  653. prev = filepath.Join(prev, p)
  654. syscall.Unlink(filepath.Join(initLayer, prev))
  655. }
  656. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  657. if os.IsNotExist(err) {
  658. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  659. return err
  660. }
  661. switch typ {
  662. case "dir":
  663. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  664. return err
  665. }
  666. case "file":
  667. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  668. if err != nil {
  669. return err
  670. }
  671. f.Chown(rootUID, rootGID)
  672. f.Close()
  673. default:
  674. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  675. return err
  676. }
  677. }
  678. } else {
  679. return err
  680. }
  681. }
  682. }
  683. // Layer is ready to use, if it wasn't before.
  684. return nil
  685. }
  686. // Parse the remapped root (user namespace) option, which can be one of:
  687. // username - valid username from /etc/passwd
  688. // username:groupname - valid username; valid groupname from /etc/group
  689. // uid - 32-bit unsigned int valid Linux UID value
  690. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  691. //
  692. // If no groupname is specified, and a username is specified, an attempt
  693. // will be made to lookup a gid for that username as a groupname
  694. //
  695. // If names are used, they are verified to exist in passwd/group
  696. func parseRemappedRoot(usergrp string) (string, string, error) {
  697. var (
  698. userID, groupID int
  699. username, groupname string
  700. )
  701. idparts := strings.Split(usergrp, ":")
  702. if len(idparts) > 2 {
  703. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  704. }
  705. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  706. // must be a uid; take it as valid
  707. userID = int(uid)
  708. luser, err := user.LookupUid(userID)
  709. if err != nil {
  710. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  711. }
  712. username = luser.Name
  713. if len(idparts) == 1 {
  714. // if the uid was numeric and no gid was specified, take the uid as the gid
  715. groupID = userID
  716. lgrp, err := user.LookupGid(groupID)
  717. if err != nil {
  718. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  719. }
  720. groupname = lgrp.Name
  721. }
  722. } else {
  723. lookupName := idparts[0]
  724. // special case: if the user specified "default", they want Docker to create or
  725. // use (after creation) the "dockremap" user/group for root remapping
  726. if lookupName == defaultIDSpecifier {
  727. lookupName = defaultRemappedID
  728. }
  729. luser, err := user.LookupUser(lookupName)
  730. if err != nil && idparts[0] != defaultIDSpecifier {
  731. // error if the name requested isn't the special "dockremap" ID
  732. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  733. } else if err != nil {
  734. // special case-- if the username == "default", then we have been asked
  735. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  736. // ranges will be used for the user and group mappings in user namespaced containers
  737. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  738. if err == nil {
  739. return defaultRemappedID, defaultRemappedID, nil
  740. }
  741. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  742. }
  743. userID = luser.Uid
  744. username = luser.Name
  745. if len(idparts) == 1 {
  746. // we only have a string username, and no group specified; look up gid from username as group
  747. group, err := user.LookupGroup(lookupName)
  748. if err != nil {
  749. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  750. }
  751. groupID = group.Gid
  752. groupname = group.Name
  753. }
  754. }
  755. if len(idparts) == 2 {
  756. // groupname or gid is separately specified and must be resolved
  757. // to a unsigned 32-bit gid
  758. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  759. // must be a gid, take it as valid
  760. groupID = int(gid)
  761. lgrp, err := user.LookupGid(groupID)
  762. if err != nil {
  763. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  764. }
  765. groupname = lgrp.Name
  766. } else {
  767. // not a number; attempt a lookup
  768. group, err := user.LookupGroup(idparts[1])
  769. if err != nil {
  770. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", idparts[1], err)
  771. }
  772. groupID = group.Gid
  773. groupname = idparts[1]
  774. }
  775. }
  776. return username, groupname, nil
  777. }
  778. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  779. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  780. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  781. }
  782. // if the daemon was started with remapped root option, parse
  783. // the config option to the int uid,gid values
  784. var (
  785. uidMaps, gidMaps []idtools.IDMap
  786. )
  787. if config.RemappedRoot != "" {
  788. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  789. if err != nil {
  790. return nil, nil, err
  791. }
  792. if username == "root" {
  793. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  794. // effectively
  795. logrus.Warnf("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  796. return uidMaps, gidMaps, nil
  797. }
  798. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  799. // update remapped root setting now that we have resolved them to actual names
  800. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  801. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  802. if err != nil {
  803. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  804. }
  805. }
  806. return uidMaps, gidMaps, nil
  807. }
  808. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  809. config.Root = rootDir
  810. // the docker root metadata directory needs to have execute permissions for all users (o+x)
  811. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  812. // (e.g. mounted layers of a container) can traverse this path.
  813. // The user namespace support will create subdirectories for the remapped root host uid:gid
  814. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  815. // layer content subtrees.
  816. if _, err := os.Stat(rootDir); err == nil {
  817. // root current exists; verify the access bits are correct by setting them
  818. if err = os.Chmod(rootDir, 0701); err != nil {
  819. return err
  820. }
  821. } else if os.IsNotExist(err) {
  822. // no root exists yet, create it 0701 with root:root ownership
  823. if err := os.MkdirAll(rootDir, 0701); err != nil {
  824. return err
  825. }
  826. }
  827. // if user namespaces are enabled we will create a subtree underneath the specified root
  828. // with any/all specified remapped root uid/gid options on the daemon creating
  829. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  830. // `chdir()` to work for containers namespaced to that uid/gid)
  831. if config.RemappedRoot != "" {
  832. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  833. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  834. // Create the root directory if it doesn't exists
  835. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  836. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  837. }
  838. }
  839. return nil
  840. }
  841. // registerLinks writes the links to a file.
  842. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  843. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  844. return nil
  845. }
  846. for _, l := range hostConfig.Links {
  847. name, alias, err := runconfigopts.ParseLink(l)
  848. if err != nil {
  849. return err
  850. }
  851. child, err := daemon.GetContainer(name)
  852. if err != nil {
  853. //An error from daemon.GetContainer() means this name could not be found
  854. return fmt.Errorf("Could not get container for %s", name)
  855. }
  856. for child.HostConfig.NetworkMode.IsContainer() {
  857. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  858. child, err = daemon.GetContainer(parts[1])
  859. if err != nil {
  860. return fmt.Errorf("Could not get container for %s", parts[1])
  861. }
  862. }
  863. if child.HostConfig.NetworkMode.IsHost() {
  864. return runconfig.ErrConflictHostNetworkAndLinks
  865. }
  866. if err := daemon.registerLink(container, child, alias); err != nil {
  867. return err
  868. }
  869. }
  870. // After we load all the links into the daemon
  871. // set them to nil on the hostconfig
  872. return container.WriteHostConfig()
  873. }
  874. // conditionalMountOnStart is a platform specific helper function during the
  875. // container start to call mount.
  876. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  877. return daemon.Mount(container)
  878. }
  879. // conditionalUnmountOnCleanup is a platform specific helper function called
  880. // during the cleanup of a container to unmount.
  881. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) {
  882. daemon.Unmount(container)
  883. }
  884. func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
  885. // Unix has no custom images to register
  886. return nil
  887. }