daemon_unix.go 23 KB

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