daemon_unix.go 24 KB

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