daemon_unix.go 25 KB

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