daemon_unix.go 23 KB

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