daemon_unix.go 35 KB

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