daemon_unix.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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) ([]string, error) {
  195. warnings := []string{}
  196. sysInfo := sysinfo.New(true)
  197. // memory subsystem checks and adjustments
  198. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  199. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  200. }
  201. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  202. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  203. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  204. resources.Memory = 0
  205. resources.MemorySwap = -1
  206. }
  207. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  208. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  209. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  210. resources.MemorySwap = -1
  211. }
  212. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  213. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  214. }
  215. if resources.Memory == 0 && resources.MemorySwap > 0 {
  216. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  217. }
  218. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  219. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  220. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  221. resources.MemorySwappiness = nil
  222. }
  223. if resources.MemorySwappiness != nil {
  224. swappiness := *resources.MemorySwappiness
  225. if swappiness < -1 || swappiness > 100 {
  226. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  227. }
  228. }
  229. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  230. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  231. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  232. resources.MemoryReservation = 0
  233. }
  234. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  235. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage.")
  236. }
  237. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  238. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  239. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  240. resources.KernelMemory = 0
  241. }
  242. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  243. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  244. }
  245. if resources.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  246. 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.")
  247. 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.")
  248. }
  249. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  250. resources.OomKillDisable = nil
  251. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  252. }
  253. // cpu subsystem checks and adjustments
  254. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  255. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  256. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  257. resources.CPUShares = 0
  258. }
  259. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  260. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  261. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  262. resources.CPUPeriod = 0
  263. }
  264. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  265. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  266. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  267. resources.CPUQuota = 0
  268. }
  269. // cpuset subsystem checks and adjustments
  270. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  271. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  272. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  273. resources.CpusetCpus = ""
  274. resources.CpusetMems = ""
  275. }
  276. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  277. if err != nil {
  278. return warnings, derr.ErrorCodeInvalidCpusetCpus.WithArgs(resources.CpusetCpus)
  279. }
  280. if !cpusAvailable {
  281. return warnings, derr.ErrorCodeNotAvailableCpusetCpus.WithArgs(resources.CpusetCpus, sysInfo.Cpus)
  282. }
  283. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  284. if err != nil {
  285. return warnings, derr.ErrorCodeInvalidCpusetMems.WithArgs(resources.CpusetMems)
  286. }
  287. if !memsAvailable {
  288. return warnings, derr.ErrorCodeNotAvailableCpusetMems.WithArgs(resources.CpusetMems, sysInfo.Mems)
  289. }
  290. // blkio subsystem checks and adjustments
  291. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  292. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  293. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  294. resources.BlkioWeight = 0
  295. }
  296. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  297. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  298. }
  299. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  300. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  301. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  302. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  303. }
  304. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  305. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  306. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  307. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  308. }
  309. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  310. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  311. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  312. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  313. }
  314. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  315. warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
  316. logrus.Warnf("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
  317. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  318. }
  319. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  320. warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
  321. logrus.Warnf("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
  322. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  323. }
  324. return warnings, nil
  325. }
  326. // verifyPlatformContainerSettings performs platform-specific validation of the
  327. // hostconfig and config structures.
  328. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config) ([]string, error) {
  329. warnings := []string{}
  330. sysInfo := sysinfo.New(true)
  331. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  332. if err != nil {
  333. return warnings, err
  334. }
  335. w, err := verifyContainerResources(&hostConfig.Resources)
  336. if err != nil {
  337. return warnings, err
  338. }
  339. warnings = append(warnings, w...)
  340. if hostConfig.ShmSize < 0 {
  341. return warnings, fmt.Errorf("SHM size must be greater then 0")
  342. }
  343. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  344. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000].", hostConfig.OomScoreAdj)
  345. }
  346. if sysInfo.IPv4ForwardingDisabled {
  347. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  348. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  349. }
  350. // check for various conflicting options with user namespaces
  351. if daemon.configStore.RemappedRoot != "" {
  352. if hostConfig.Privileged {
  353. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces.")
  354. }
  355. if hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsContainer() {
  356. return warnings, fmt.Errorf("Cannot share the host or a container's network namespace when user namespaces are enabled.")
  357. }
  358. if hostConfig.PidMode.IsHost() {
  359. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled.")
  360. }
  361. if hostConfig.IpcMode.IsContainer() {
  362. return warnings, fmt.Errorf("Cannot share a container's IPC namespace when user namespaces are enabled.")
  363. }
  364. if hostConfig.ReadonlyRootfs {
  365. return warnings, fmt.Errorf("Cannot use the --read-only option when user namespaces are enabled.")
  366. }
  367. }
  368. return warnings, nil
  369. }
  370. // checkConfigOptions checks for mutually incompatible config options
  371. func checkConfigOptions(config *Config) error {
  372. // Check for mutually incompatible config options
  373. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  374. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  375. }
  376. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  377. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true.")
  378. }
  379. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  380. config.Bridge.EnableIPMasq = false
  381. }
  382. return nil
  383. }
  384. // checkSystem validates platform-specific requirements
  385. func checkSystem() error {
  386. if os.Geteuid() != 0 {
  387. return fmt.Errorf("The Docker daemon needs to be run as root")
  388. }
  389. return checkKernel()
  390. }
  391. // configureKernelSecuritySupport configures and validate security support for the kernel
  392. func configureKernelSecuritySupport(config *Config, driverName string) error {
  393. if config.EnableSelinuxSupport {
  394. if selinuxEnabled() {
  395. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  396. if driverName == "overlay" {
  397. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  398. }
  399. logrus.Debug("SELinux enabled successfully")
  400. } else {
  401. logrus.Warn("Docker could not enable SELinux on the host system")
  402. }
  403. } else {
  404. selinuxSetDisabled()
  405. }
  406. return nil
  407. }
  408. func isBridgeNetworkDisabled(config *Config) bool {
  409. return config.Bridge.Iface == disableNetworkBridge
  410. }
  411. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  412. options := []nwconfig.Option{}
  413. if dconfig == nil {
  414. return options, nil
  415. }
  416. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  417. dd := runconfig.DefaultDaemonNetworkMode()
  418. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  419. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  420. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  421. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  422. kv := strings.Split(dconfig.ClusterStore, "://")
  423. if len(kv) != 2 {
  424. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  425. }
  426. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  427. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  428. }
  429. if len(dconfig.ClusterOpts) > 0 {
  430. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  431. }
  432. if daemon.discoveryWatcher != nil {
  433. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  434. }
  435. if dconfig.ClusterAdvertise != "" {
  436. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  437. }
  438. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  439. options = append(options, driverOptions(dconfig)...)
  440. return options, nil
  441. }
  442. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  443. netOptions, err := daemon.networkOptions(config)
  444. if err != nil {
  445. return nil, err
  446. }
  447. controller, err := libnetwork.New(netOptions...)
  448. if err != nil {
  449. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  450. }
  451. // Initialize default network on "null"
  452. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  453. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  454. }
  455. // Initialize default network on "host"
  456. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  457. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  458. }
  459. if !config.DisableBridge {
  460. // Initialize default driver "bridge"
  461. if err := initBridgeDriver(controller, config); err != nil {
  462. return nil, err
  463. }
  464. }
  465. return controller, nil
  466. }
  467. func driverOptions(config *Config) []nwconfig.Option {
  468. bridgeConfig := options.Generic{
  469. "EnableIPForwarding": config.Bridge.EnableIPForward,
  470. "EnableIPTables": config.Bridge.EnableIPTables,
  471. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy}
  472. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  473. dOptions := []nwconfig.Option{}
  474. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  475. return dOptions
  476. }
  477. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  478. if n, err := controller.NetworkByName("bridge"); err == nil {
  479. if err = n.Delete(); err != nil {
  480. return fmt.Errorf("could not delete the default bridge network: %v", err)
  481. }
  482. }
  483. bridgeName := bridge.DefaultBridgeName
  484. if config.Bridge.Iface != "" {
  485. bridgeName = config.Bridge.Iface
  486. }
  487. netOption := map[string]string{
  488. bridge.BridgeName: bridgeName,
  489. bridge.DefaultBridge: strconv.FormatBool(true),
  490. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  491. bridge.EnableIPMasquerade: strconv.FormatBool(config.Bridge.EnableIPMasq),
  492. bridge.EnableICC: strconv.FormatBool(config.Bridge.InterContainerCommunication),
  493. }
  494. // --ip processing
  495. if config.Bridge.DefaultIP != nil {
  496. netOption[bridge.DefaultBindingIP] = config.Bridge.DefaultIP.String()
  497. }
  498. ipamV4Conf := libnetwork.IpamConf{}
  499. ipamV4Conf.AuxAddresses = make(map[string]string)
  500. if nw, _, err := ipamutils.ElectInterfaceAddresses(bridgeName); err == nil {
  501. ipamV4Conf.PreferredPool = nw.String()
  502. hip, _ := types.GetHostPartIP(nw.IP, nw.Mask)
  503. if hip.IsGlobalUnicast() {
  504. ipamV4Conf.Gateway = nw.IP.String()
  505. }
  506. }
  507. if config.Bridge.IP != "" {
  508. ipamV4Conf.PreferredPool = config.Bridge.IP
  509. ip, _, err := net.ParseCIDR(config.Bridge.IP)
  510. if err != nil {
  511. return err
  512. }
  513. ipamV4Conf.Gateway = ip.String()
  514. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  515. 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)
  516. }
  517. if config.Bridge.FixedCIDR != "" {
  518. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  519. if err != nil {
  520. return err
  521. }
  522. ipamV4Conf.SubPool = fCIDR.String()
  523. }
  524. if config.Bridge.DefaultGatewayIPv4 != nil {
  525. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4.String()
  526. }
  527. var (
  528. ipamV6Conf *libnetwork.IpamConf
  529. deferIPv6Alloc bool
  530. )
  531. if config.Bridge.FixedCIDRv6 != "" {
  532. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  533. if err != nil {
  534. return err
  535. }
  536. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  537. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  538. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  539. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  540. // on this network until after the driver has created the endpoint and returned the
  541. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  542. ones, _ := fCIDRv6.Mask.Size()
  543. deferIPv6Alloc = ones <= 80
  544. if ipamV6Conf == nil {
  545. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  546. }
  547. ipamV6Conf.PreferredPool = fCIDRv6.String()
  548. }
  549. if config.Bridge.DefaultGatewayIPv6 != nil {
  550. if ipamV6Conf == nil {
  551. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  552. }
  553. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6.String()
  554. }
  555. v4Conf := []*libnetwork.IpamConf{&ipamV4Conf}
  556. v6Conf := []*libnetwork.IpamConf{}
  557. if ipamV6Conf != nil {
  558. v6Conf = append(v6Conf, ipamV6Conf)
  559. }
  560. // Initialize default network on "bridge" with the same name
  561. _, err := controller.NewNetwork("bridge", "bridge",
  562. libnetwork.NetworkOptionGeneric(options.Generic{
  563. netlabel.GenericData: netOption,
  564. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  565. }),
  566. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  567. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  568. if err != nil {
  569. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  570. }
  571. return nil
  572. }
  573. // setupInitLayer populates a directory with mountpoints suitable
  574. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  575. // empty file at /.dockerinit
  576. //
  577. // This extra layer is used by all containers as the top-most ro layer. It protects
  578. // the container from unwanted side-effects on the rw layer.
  579. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  580. for pth, typ := range map[string]string{
  581. "/dev/pts": "dir",
  582. "/dev/shm": "dir",
  583. "/proc": "dir",
  584. "/sys": "dir",
  585. "/.dockerinit": "file",
  586. "/.dockerenv": "file",
  587. "/etc/resolv.conf": "file",
  588. "/etc/hosts": "file",
  589. "/etc/hostname": "file",
  590. "/dev/console": "file",
  591. "/etc/mtab": "/proc/mounts",
  592. } {
  593. parts := strings.Split(pth, "/")
  594. prev := "/"
  595. for _, p := range parts[1:] {
  596. prev = filepath.Join(prev, p)
  597. syscall.Unlink(filepath.Join(initLayer, prev))
  598. }
  599. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  600. if os.IsNotExist(err) {
  601. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  602. return err
  603. }
  604. switch typ {
  605. case "dir":
  606. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  607. return err
  608. }
  609. case "file":
  610. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  611. if err != nil {
  612. return err
  613. }
  614. f.Chown(rootUID, rootGID)
  615. f.Close()
  616. default:
  617. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  618. return err
  619. }
  620. }
  621. } else {
  622. return err
  623. }
  624. }
  625. }
  626. // Layer is ready to use, if it wasn't before.
  627. return nil
  628. }
  629. // Parse the remapped root (user namespace) option, which can be one of:
  630. // username - valid username from /etc/passwd
  631. // username:groupname - valid username; valid groupname from /etc/group
  632. // uid - 32-bit unsigned int valid Linux UID value
  633. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  634. //
  635. // If no groupname is specified, and a username is specified, an attempt
  636. // will be made to lookup a gid for that username as a groupname
  637. //
  638. // If names are used, they are verified to exist in passwd/group
  639. func parseRemappedRoot(usergrp string) (string, string, error) {
  640. var (
  641. userID, groupID int
  642. username, groupname string
  643. )
  644. idparts := strings.Split(usergrp, ":")
  645. if len(idparts) > 2 {
  646. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  647. }
  648. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  649. // must be a uid; take it as valid
  650. userID = int(uid)
  651. luser, err := user.LookupUid(userID)
  652. if err != nil {
  653. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  654. }
  655. username = luser.Name
  656. if len(idparts) == 1 {
  657. // if the uid was numeric and no gid was specified, take the uid as the gid
  658. groupID = userID
  659. lgrp, err := user.LookupGid(groupID)
  660. if err != nil {
  661. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  662. }
  663. groupname = lgrp.Name
  664. }
  665. } else {
  666. lookupName := idparts[0]
  667. // special case: if the user specified "default", they want Docker to create or
  668. // use (after creation) the "dockremap" user/group for root remapping
  669. if lookupName == defaultIDSpecifier {
  670. lookupName = defaultRemappedID
  671. }
  672. luser, err := user.LookupUser(lookupName)
  673. if err != nil && idparts[0] != defaultIDSpecifier {
  674. // error if the name requested isn't the special "dockremap" ID
  675. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  676. } else if err != nil {
  677. // special case-- if the username == "default", then we have been asked
  678. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  679. // ranges will be used for the user and group mappings in user namespaced containers
  680. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  681. if err == nil {
  682. return defaultRemappedID, defaultRemappedID, nil
  683. }
  684. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  685. }
  686. userID = luser.Uid
  687. username = luser.Name
  688. if len(idparts) == 1 {
  689. // we only have a string username, and no group specified; look up gid from username as group
  690. group, err := user.LookupGroup(lookupName)
  691. if err != nil {
  692. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  693. }
  694. groupID = group.Gid
  695. groupname = group.Name
  696. }
  697. }
  698. if len(idparts) == 2 {
  699. // groupname or gid is separately specified and must be resolved
  700. // to a unsigned 32-bit gid
  701. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  702. // must be a gid, take it as valid
  703. groupID = int(gid)
  704. lgrp, err := user.LookupGid(groupID)
  705. if err != nil {
  706. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  707. }
  708. groupname = lgrp.Name
  709. } else {
  710. // not a number; attempt a lookup
  711. group, err := user.LookupGroup(idparts[1])
  712. if err != nil {
  713. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", idparts[1], err)
  714. }
  715. groupID = group.Gid
  716. groupname = idparts[1]
  717. }
  718. }
  719. return username, groupname, nil
  720. }
  721. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  722. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  723. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  724. }
  725. // if the daemon was started with remapped root option, parse
  726. // the config option to the int uid,gid values
  727. var (
  728. uidMaps, gidMaps []idtools.IDMap
  729. )
  730. if config.RemappedRoot != "" {
  731. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  732. if err != nil {
  733. return nil, nil, err
  734. }
  735. if username == "root" {
  736. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  737. // effectively
  738. logrus.Warnf("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  739. return uidMaps, gidMaps, nil
  740. }
  741. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  742. // update remapped root setting now that we have resolved them to actual names
  743. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  744. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  745. if err != nil {
  746. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  747. }
  748. }
  749. return uidMaps, gidMaps, nil
  750. }
  751. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  752. config.Root = rootDir
  753. // the docker root metadata directory needs to have execute permissions for all users (o+x)
  754. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  755. // (e.g. mounted layers of a container) can traverse this path.
  756. // The user namespace support will create subdirectories for the remapped root host uid:gid
  757. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  758. // layer content subtrees.
  759. if _, err := os.Stat(rootDir); err == nil {
  760. // root current exists; verify the access bits are correct by setting them
  761. if err = os.Chmod(rootDir, 0701); err != nil {
  762. return err
  763. }
  764. } else if os.IsNotExist(err) {
  765. // no root exists yet, create it 0701 with root:root ownership
  766. if err := os.MkdirAll(rootDir, 0701); err != nil {
  767. return err
  768. }
  769. }
  770. // if user namespaces are enabled we will create a subtree underneath the specified root
  771. // with any/all specified remapped root uid/gid options on the daemon creating
  772. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  773. // `chdir()` to work for containers namespaced to that uid/gid)
  774. if config.RemappedRoot != "" {
  775. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  776. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  777. // Create the root directory if it doesn't exists
  778. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  779. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  780. }
  781. }
  782. return nil
  783. }
  784. // registerLinks writes the links to a file.
  785. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  786. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  787. return nil
  788. }
  789. for _, l := range hostConfig.Links {
  790. name, alias, err := runconfigopts.ParseLink(l)
  791. if err != nil {
  792. return err
  793. }
  794. child, err := daemon.GetContainer(name)
  795. if err != nil {
  796. //An error from daemon.GetContainer() means this name could not be found
  797. return fmt.Errorf("Could not get container for %s", name)
  798. }
  799. for child.HostConfig.NetworkMode.IsContainer() {
  800. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  801. child, err = daemon.GetContainer(parts[1])
  802. if err != nil {
  803. return fmt.Errorf("Could not get container for %s", parts[1])
  804. }
  805. }
  806. if child.HostConfig.NetworkMode.IsHost() {
  807. return runconfig.ErrConflictHostNetworkAndLinks
  808. }
  809. if err := daemon.registerLink(container, child, alias); err != nil {
  810. return err
  811. }
  812. }
  813. // After we load all the links into the daemon
  814. // set them to nil on the hostconfig
  815. return container.WriteHostConfig()
  816. }
  817. // conditionalMountOnStart is a platform specific helper function during the
  818. // container start to call mount.
  819. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  820. return daemon.Mount(container)
  821. }
  822. // conditionalUnmountOnCleanup is a platform specific helper function called
  823. // during the cleanup of a container to unmount.
  824. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) {
  825. daemon.Unmount(container)
  826. }
  827. func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
  828. // Unix has no custom images to register
  829. return nil
  830. }