daemon_unix.go 25 KB

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