daemon_unix.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/graphdriver"
  14. derr "github.com/docker/docker/errors"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/layer"
  17. pblkiodev "github.com/docker/docker/pkg/blkiodev"
  18. "github.com/docker/docker/pkg/idtools"
  19. "github.com/docker/docker/pkg/parsers"
  20. "github.com/docker/docker/pkg/parsers/kernel"
  21. "github.com/docker/docker/pkg/sysinfo"
  22. "github.com/docker/docker/runconfig"
  23. "github.com/docker/docker/tag"
  24. "github.com/docker/libnetwork"
  25. nwconfig "github.com/docker/libnetwork/config"
  26. "github.com/docker/libnetwork/drivers/bridge"
  27. "github.com/docker/libnetwork/ipamutils"
  28. "github.com/docker/libnetwork/netlabel"
  29. "github.com/docker/libnetwork/options"
  30. "github.com/docker/libnetwork/types"
  31. blkiodev "github.com/opencontainers/runc/libcontainer/configs"
  32. "github.com/opencontainers/runc/libcontainer/label"
  33. )
  34. const (
  35. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  36. linuxMinCPUShares = 2
  37. linuxMaxCPUShares = 262144
  38. platformSupported = true
  39. )
  40. func getBlkioWeightDevices(config *runconfig.HostConfig) ([]*blkiodev.WeightDevice, error) {
  41. var stat syscall.Stat_t
  42. var BlkioWeightDevices []*blkiodev.WeightDevice
  43. for _, weightDevice := range config.BlkioWeightDevice {
  44. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  45. return nil, err
  46. }
  47. WeightDevice := blkiodev.NewWeightDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), weightDevice.Weight, 0)
  48. BlkioWeightDevices = append(BlkioWeightDevices, WeightDevice)
  49. }
  50. return BlkioWeightDevices, nil
  51. }
  52. func parseSecurityOpt(container *container.Container, config *runconfig.HostConfig) error {
  53. var (
  54. labelOpts []string
  55. err error
  56. )
  57. for _, opt := range config.SecurityOpt {
  58. con := strings.SplitN(opt, ":", 2)
  59. if len(con) == 1 {
  60. return fmt.Errorf("Invalid --security-opt: %q", opt)
  61. }
  62. switch con[0] {
  63. case "label":
  64. labelOpts = append(labelOpts, con[1])
  65. case "apparmor":
  66. container.AppArmorProfile = con[1]
  67. case "seccomp":
  68. container.SeccompProfile = con[1]
  69. default:
  70. return fmt.Errorf("Invalid --security-opt: %q", opt)
  71. }
  72. }
  73. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  74. return err
  75. }
  76. func getBlkioReadBpsDevices(config *runconfig.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  77. var BlkioReadBpsDevice []*blkiodev.ThrottleDevice
  78. var stat syscall.Stat_t
  79. for _, bpsDevice := range config.BlkioDeviceReadBps {
  80. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  81. return nil, err
  82. }
  83. ReadBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  84. BlkioReadBpsDevice = append(BlkioReadBpsDevice, ReadBpsDevice)
  85. }
  86. return BlkioReadBpsDevice, nil
  87. }
  88. func getBlkioWriteBpsDevices(config *runconfig.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  89. var BlkioWriteBpsDevice []*blkiodev.ThrottleDevice
  90. var stat syscall.Stat_t
  91. for _, bpsDevice := range config.BlkioDeviceWriteBps {
  92. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  93. return nil, err
  94. }
  95. WriteBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  96. BlkioWriteBpsDevice = append(BlkioWriteBpsDevice, WriteBpsDevice)
  97. }
  98. return BlkioWriteBpsDevice, nil
  99. }
  100. func checkKernelVersion(k, major, minor int) bool {
  101. if v, err := kernel.GetKernelVersion(); err != nil {
  102. logrus.Warnf("%s", err)
  103. } else {
  104. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  105. return false
  106. }
  107. }
  108. return true
  109. }
  110. func checkKernel() error {
  111. // Check for unsupported kernel versions
  112. // FIXME: it would be cleaner to not test for specific versions, but rather
  113. // test for specific functionalities.
  114. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  115. // without actually causing a kernel panic, so we need this workaround until
  116. // the circumstances of pre-3.10 crashes are clearer.
  117. // For details see https://github.com/docker/docker/issues/407
  118. if !checkKernelVersion(3, 10, 0) {
  119. v, _ := kernel.GetKernelVersion()
  120. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  121. logrus.Warnf("Your Linux kernel version %s can be unstable running docker. Please upgrade your kernel to 3.10.0.", v.String())
  122. }
  123. }
  124. return nil
  125. }
  126. // adaptContainerSettings is called during container creation to modify any
  127. // settings necessary in the HostConfig structure.
  128. func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig, adjustCPUShares bool) error {
  129. if adjustCPUShares && hostConfig.CPUShares > 0 {
  130. // Handle unsupported CPUShares
  131. if hostConfig.CPUShares < linuxMinCPUShares {
  132. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  133. hostConfig.CPUShares = linuxMinCPUShares
  134. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  135. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  136. hostConfig.CPUShares = linuxMaxCPUShares
  137. }
  138. }
  139. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  140. // By default, MemorySwap is set to twice the size of Memory.
  141. hostConfig.MemorySwap = hostConfig.Memory * 2
  142. }
  143. if hostConfig.ShmSize == nil {
  144. shmSize := container.DefaultSHMSize
  145. hostConfig.ShmSize = &shmSize
  146. }
  147. var err error
  148. if hostConfig.SecurityOpt == nil {
  149. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode)
  150. if err != nil {
  151. return err
  152. }
  153. }
  154. if hostConfig.MemorySwappiness == nil {
  155. defaultSwappiness := int64(-1)
  156. hostConfig.MemorySwappiness = &defaultSwappiness
  157. }
  158. return nil
  159. }
  160. // verifyPlatformContainerSettings performs platform-specific validation of the
  161. // hostconfig and config structures.
  162. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  163. warnings := []string{}
  164. sysInfo := sysinfo.New(true)
  165. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  166. if err != nil {
  167. return warnings, err
  168. }
  169. if hostConfig.ShmSize != nil && *hostConfig.ShmSize <= 0 {
  170. return warnings, fmt.Errorf("SHM size must be greater then 0")
  171. }
  172. // memory subsystem checks and adjustments
  173. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  174. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  175. }
  176. if hostConfig.Memory > 0 && !sysInfo.MemoryLimit {
  177. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  178. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  179. hostConfig.Memory = 0
  180. hostConfig.MemorySwap = -1
  181. }
  182. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !sysInfo.SwapLimit {
  183. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  184. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  185. hostConfig.MemorySwap = -1
  186. }
  187. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  188. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  189. }
  190. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  191. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  192. }
  193. if hostConfig.MemorySwappiness != nil && *hostConfig.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  194. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  195. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  196. hostConfig.MemorySwappiness = nil
  197. }
  198. if hostConfig.MemorySwappiness != nil {
  199. swappiness := *hostConfig.MemorySwappiness
  200. if swappiness < -1 || swappiness > 100 {
  201. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  202. }
  203. }
  204. if hostConfig.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  205. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  206. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  207. hostConfig.MemoryReservation = 0
  208. }
  209. if hostConfig.Memory > 0 && hostConfig.MemoryReservation > 0 && hostConfig.Memory < hostConfig.MemoryReservation {
  210. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage.")
  211. }
  212. if hostConfig.KernelMemory > 0 && !sysInfo.KernelMemory {
  213. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  214. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  215. hostConfig.KernelMemory = 0
  216. }
  217. if hostConfig.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  218. 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.")
  219. 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.")
  220. }
  221. if hostConfig.CPUShares > 0 && !sysInfo.CPUShares {
  222. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  223. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  224. hostConfig.CPUShares = 0
  225. }
  226. if hostConfig.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  227. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  228. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  229. hostConfig.CPUPeriod = 0
  230. }
  231. if hostConfig.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  232. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  233. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  234. hostConfig.CPUQuota = 0
  235. }
  236. if (hostConfig.CpusetCpus != "" || hostConfig.CpusetMems != "") && !sysInfo.Cpuset {
  237. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  238. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  239. hostConfig.CpusetCpus = ""
  240. hostConfig.CpusetMems = ""
  241. }
  242. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(hostConfig.CpusetCpus)
  243. if err != nil {
  244. return warnings, derr.ErrorCodeInvalidCpusetCpus.WithArgs(hostConfig.CpusetCpus)
  245. }
  246. if !cpusAvailable {
  247. return warnings, derr.ErrorCodeNotAvailableCpusetCpus.WithArgs(hostConfig.CpusetCpus, sysInfo.Cpus)
  248. }
  249. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(hostConfig.CpusetMems)
  250. if err != nil {
  251. return warnings, derr.ErrorCodeInvalidCpusetMems.WithArgs(hostConfig.CpusetMems)
  252. }
  253. if !memsAvailable {
  254. return warnings, derr.ErrorCodeNotAvailableCpusetMems.WithArgs(hostConfig.CpusetMems, sysInfo.Mems)
  255. }
  256. if hostConfig.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  257. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  258. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  259. hostConfig.BlkioWeight = 0
  260. }
  261. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  262. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  263. }
  264. if len(hostConfig.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  265. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  266. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  267. hostConfig.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  268. }
  269. if len(hostConfig.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  270. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  271. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  272. hostConfig.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  273. }
  274. if len(hostConfig.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  275. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  276. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  277. hostConfig.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  278. }
  279. if hostConfig.OomKillDisable && !sysInfo.OomKillDisable {
  280. hostConfig.OomKillDisable = false
  281. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  282. }
  283. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  284. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000].", hostConfig.OomScoreAdj)
  285. }
  286. if sysInfo.IPv4ForwardingDisabled {
  287. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  288. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  289. }
  290. return warnings, nil
  291. }
  292. // checkConfigOptions checks for mutually incompatible config options
  293. func checkConfigOptions(config *Config) error {
  294. // Check for mutually incompatible config options
  295. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  296. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  297. }
  298. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  299. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true.")
  300. }
  301. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  302. config.Bridge.EnableIPMasq = false
  303. }
  304. return nil
  305. }
  306. // checkSystem validates platform-specific requirements
  307. func checkSystem() error {
  308. if os.Geteuid() != 0 {
  309. return fmt.Errorf("The Docker daemon needs to be run as root")
  310. }
  311. return checkKernel()
  312. }
  313. // configureKernelSecuritySupport configures and validate security support for the kernel
  314. func configureKernelSecuritySupport(config *Config, driverName string) error {
  315. if config.EnableSelinuxSupport {
  316. if selinuxEnabled() {
  317. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  318. if driverName == "overlay" {
  319. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  320. }
  321. logrus.Debug("SELinux enabled successfully")
  322. } else {
  323. logrus.Warn("Docker could not enable SELinux on the host system")
  324. }
  325. } else {
  326. selinuxSetDisabled()
  327. }
  328. return nil
  329. }
  330. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  331. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  332. return migrateIfAufs(driver, root)
  333. }
  334. func isBridgeNetworkDisabled(config *Config) bool {
  335. return config.Bridge.Iface == disableNetworkBridge
  336. }
  337. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  338. options := []nwconfig.Option{}
  339. if dconfig == nil {
  340. return options, nil
  341. }
  342. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  343. dd := runconfig.DefaultDaemonNetworkMode()
  344. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  345. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  346. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  347. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  348. kv := strings.Split(dconfig.ClusterStore, "://")
  349. if len(kv) != 2 {
  350. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  351. }
  352. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  353. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  354. }
  355. if len(dconfig.ClusterOpts) > 0 {
  356. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  357. }
  358. if daemon.discoveryWatcher != nil {
  359. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  360. }
  361. if dconfig.ClusterAdvertise != "" {
  362. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  363. }
  364. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  365. options = append(options, driverOptions(dconfig)...)
  366. return options, nil
  367. }
  368. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  369. netOptions, err := daemon.networkOptions(config)
  370. if err != nil {
  371. return nil, err
  372. }
  373. controller, err := libnetwork.New(netOptions...)
  374. if err != nil {
  375. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  376. }
  377. // Initialize default network on "null"
  378. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  379. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  380. }
  381. // Initialize default network on "host"
  382. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  383. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  384. }
  385. if !config.DisableBridge {
  386. // Initialize default driver "bridge"
  387. if err := initBridgeDriver(controller, config); err != nil {
  388. return nil, err
  389. }
  390. }
  391. return controller, nil
  392. }
  393. func driverOptions(config *Config) []nwconfig.Option {
  394. bridgeConfig := options.Generic{
  395. "EnableIPForwarding": config.Bridge.EnableIPForward,
  396. "EnableIPTables": config.Bridge.EnableIPTables,
  397. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy}
  398. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  399. dOptions := []nwconfig.Option{}
  400. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  401. return dOptions
  402. }
  403. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  404. if n, err := controller.NetworkByName("bridge"); err == nil {
  405. if err = n.Delete(); err != nil {
  406. return fmt.Errorf("could not delete the default bridge network: %v", err)
  407. }
  408. }
  409. bridgeName := bridge.DefaultBridgeName
  410. if config.Bridge.Iface != "" {
  411. bridgeName = config.Bridge.Iface
  412. }
  413. netOption := map[string]string{
  414. bridge.BridgeName: bridgeName,
  415. bridge.DefaultBridge: strconv.FormatBool(true),
  416. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  417. bridge.EnableIPMasquerade: strconv.FormatBool(config.Bridge.EnableIPMasq),
  418. bridge.EnableICC: strconv.FormatBool(config.Bridge.InterContainerCommunication),
  419. }
  420. // --ip processing
  421. if config.Bridge.DefaultIP != nil {
  422. netOption[bridge.DefaultBindingIP] = config.Bridge.DefaultIP.String()
  423. }
  424. ipamV4Conf := libnetwork.IpamConf{}
  425. ipamV4Conf.AuxAddresses = make(map[string]string)
  426. if nw, _, err := ipamutils.ElectInterfaceAddresses(bridgeName); err == nil {
  427. ipamV4Conf.PreferredPool = nw.String()
  428. hip, _ := types.GetHostPartIP(nw.IP, nw.Mask)
  429. if hip.IsGlobalUnicast() {
  430. ipamV4Conf.Gateway = nw.IP.String()
  431. }
  432. }
  433. if config.Bridge.IP != "" {
  434. ipamV4Conf.PreferredPool = config.Bridge.IP
  435. ip, _, err := net.ParseCIDR(config.Bridge.IP)
  436. if err != nil {
  437. return err
  438. }
  439. ipamV4Conf.Gateway = ip.String()
  440. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  441. 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)
  442. }
  443. if config.Bridge.FixedCIDR != "" {
  444. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  445. if err != nil {
  446. return err
  447. }
  448. ipamV4Conf.SubPool = fCIDR.String()
  449. }
  450. if config.Bridge.DefaultGatewayIPv4 != nil {
  451. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4.String()
  452. }
  453. var (
  454. ipamV6Conf *libnetwork.IpamConf
  455. deferIPv6Alloc bool
  456. )
  457. if config.Bridge.FixedCIDRv6 != "" {
  458. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  459. if err != nil {
  460. return err
  461. }
  462. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  463. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  464. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  465. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  466. // on this network until after the driver has created the endpoint and returned the
  467. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  468. ones, _ := fCIDRv6.Mask.Size()
  469. deferIPv6Alloc = ones <= 80
  470. if ipamV6Conf == nil {
  471. ipamV6Conf = &libnetwork.IpamConf{}
  472. }
  473. ipamV6Conf.PreferredPool = fCIDRv6.String()
  474. }
  475. if config.Bridge.DefaultGatewayIPv6 != nil {
  476. if ipamV6Conf == nil {
  477. ipamV6Conf = &libnetwork.IpamConf{}
  478. }
  479. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6.String()
  480. }
  481. v4Conf := []*libnetwork.IpamConf{&ipamV4Conf}
  482. v6Conf := []*libnetwork.IpamConf{}
  483. if ipamV6Conf != nil {
  484. v6Conf = append(v6Conf, ipamV6Conf)
  485. }
  486. // Initialize default network on "bridge" with the same name
  487. _, err := controller.NewNetwork("bridge", "bridge",
  488. libnetwork.NetworkOptionGeneric(options.Generic{
  489. netlabel.GenericData: netOption,
  490. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  491. }),
  492. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf),
  493. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  494. if err != nil {
  495. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  496. }
  497. return nil
  498. }
  499. // setupInitLayer populates a directory with mountpoints suitable
  500. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  501. // empty file at /.dockerinit
  502. //
  503. // This extra layer is used by all containers as the top-most ro layer. It protects
  504. // the container from unwanted side-effects on the rw layer.
  505. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  506. for pth, typ := range map[string]string{
  507. "/dev/pts": "dir",
  508. "/dev/shm": "dir",
  509. "/proc": "dir",
  510. "/sys": "dir",
  511. "/.dockerinit": "file",
  512. "/.dockerenv": "file",
  513. "/etc/resolv.conf": "file",
  514. "/etc/hosts": "file",
  515. "/etc/hostname": "file",
  516. "/dev/console": "file",
  517. "/etc/mtab": "/proc/mounts",
  518. } {
  519. parts := strings.Split(pth, "/")
  520. prev := "/"
  521. for _, p := range parts[1:] {
  522. prev = filepath.Join(prev, p)
  523. syscall.Unlink(filepath.Join(initLayer, prev))
  524. }
  525. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  526. if os.IsNotExist(err) {
  527. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  528. return err
  529. }
  530. switch typ {
  531. case "dir":
  532. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  533. return err
  534. }
  535. case "file":
  536. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  537. if err != nil {
  538. return err
  539. }
  540. f.Chown(rootUID, rootGID)
  541. f.Close()
  542. default:
  543. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  544. return err
  545. }
  546. }
  547. } else {
  548. return err
  549. }
  550. }
  551. }
  552. // Layer is ready to use, if it wasn't before.
  553. return nil
  554. }
  555. // registerLinks writes the links to a file.
  556. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *runconfig.HostConfig) error {
  557. if hostConfig == nil || hostConfig.Links == nil {
  558. return nil
  559. }
  560. for _, l := range hostConfig.Links {
  561. name, alias, err := parsers.ParseLink(l)
  562. if err != nil {
  563. return err
  564. }
  565. child, err := daemon.Get(name)
  566. if err != nil {
  567. //An error from daemon.Get() means this name could not be found
  568. return fmt.Errorf("Could not get container for %s", name)
  569. }
  570. for child.HostConfig.NetworkMode.IsContainer() {
  571. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  572. child, err = daemon.Get(parts[1])
  573. if err != nil {
  574. return fmt.Errorf("Could not get container for %s", parts[1])
  575. }
  576. }
  577. if child.HostConfig.NetworkMode.IsHost() {
  578. return runconfig.ErrConflictHostNetworkAndLinks
  579. }
  580. if err := daemon.registerLink(container, child, alias); err != nil {
  581. return err
  582. }
  583. }
  584. // After we load all the links into the daemon
  585. // set them to nil on the hostconfig
  586. hostConfig.Links = nil
  587. if err := container.WriteHostConfig(); err != nil {
  588. return err
  589. }
  590. return nil
  591. }
  592. // conditionalMountOnStart is a platform specific helper function during the
  593. // container start to call mount.
  594. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  595. return daemon.Mount(container)
  596. }
  597. // conditionalUnmountOnCleanup is a platform specific helper function called
  598. // during the cleanup of a container to unmount.
  599. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) {
  600. daemon.Unmount(container)
  601. }
  602. func restoreCustomImage(driver graphdriver.Driver, is image.Store, ls layer.Store, ts tag.Store) error {
  603. // Unix has no custom images to register
  604. return nil
  605. }