daemon_unix.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "syscall"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/docker/autogen/dockerversion"
  12. "github.com/docker/docker/daemon/graphdriver"
  13. derr "github.com/docker/docker/errors"
  14. "github.com/docker/docker/pkg/fileutils"
  15. "github.com/docker/docker/pkg/parsers"
  16. "github.com/docker/docker/pkg/parsers/kernel"
  17. "github.com/docker/docker/pkg/sysinfo"
  18. "github.com/docker/docker/pkg/system"
  19. "github.com/docker/docker/runconfig"
  20. "github.com/docker/docker/utils"
  21. "github.com/docker/libnetwork"
  22. nwconfig "github.com/docker/libnetwork/config"
  23. "github.com/docker/libnetwork/netlabel"
  24. "github.com/docker/libnetwork/options"
  25. "github.com/opencontainers/runc/libcontainer/label"
  26. "github.com/vishvananda/netlink"
  27. )
  28. const (
  29. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  30. linuxMinCPUShares = 2
  31. linuxMaxCPUShares = 262144
  32. platformSupported = true
  33. )
  34. func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
  35. var (
  36. labelOpts []string
  37. err error
  38. )
  39. for _, opt := range config.SecurityOpt {
  40. con := strings.SplitN(opt, ":", 2)
  41. if len(con) == 1 {
  42. return fmt.Errorf("Invalid --security-opt: %q", opt)
  43. }
  44. switch con[0] {
  45. case "label":
  46. labelOpts = append(labelOpts, con[1])
  47. case "apparmor":
  48. container.AppArmorProfile = con[1]
  49. default:
  50. return fmt.Errorf("Invalid --security-opt: %q", opt)
  51. }
  52. }
  53. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  54. return err
  55. }
  56. func checkKernelVersion(k, major, minor int) bool {
  57. if v, err := kernel.GetKernelVersion(); err != nil {
  58. logrus.Warnf("%s", err)
  59. } else {
  60. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  61. return false
  62. }
  63. }
  64. return true
  65. }
  66. func checkKernel() error {
  67. // Check for unsupported kernel versions
  68. // FIXME: it would be cleaner to not test for specific versions, but rather
  69. // test for specific functionalities.
  70. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  71. // without actually causing a kernel panic, so we need this workaround until
  72. // the circumstances of pre-3.10 crashes are clearer.
  73. // For details see https://github.com/docker/docker/issues/407
  74. if !checkKernelVersion(3, 10, 0) {
  75. v, _ := kernel.GetKernelVersion()
  76. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  77. logrus.Warnf("Your Linux kernel version %s can be unstable running docker. Please upgrade your kernel to 3.10.0.", v.String())
  78. }
  79. }
  80. return nil
  81. }
  82. // adaptContainerSettings is called during container creation to modify any
  83. // settings necessary in the HostConfig structure.
  84. func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig, adjustCPUShares bool) {
  85. if hostConfig == nil {
  86. return
  87. }
  88. if adjustCPUShares && hostConfig.CPUShares > 0 {
  89. // Handle unsupported CPUShares
  90. if hostConfig.CPUShares < linuxMinCPUShares {
  91. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  92. hostConfig.CPUShares = linuxMinCPUShares
  93. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  94. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  95. hostConfig.CPUShares = linuxMaxCPUShares
  96. }
  97. }
  98. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  99. // By default, MemorySwap is set to twice the size of Memory.
  100. hostConfig.MemorySwap = hostConfig.Memory * 2
  101. }
  102. if hostConfig.MemoryReservation == 0 && hostConfig.Memory > 0 {
  103. hostConfig.MemoryReservation = hostConfig.Memory
  104. }
  105. }
  106. // verifyPlatformContainerSettings performs platform-specific validation of the
  107. // hostconfig and config structures.
  108. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  109. warnings := []string{}
  110. sysInfo := sysinfo.New(true)
  111. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  112. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  113. }
  114. // memory subsystem checks and adjustments
  115. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  116. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  117. }
  118. if hostConfig.Memory > 0 && !sysInfo.MemoryLimit {
  119. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  120. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  121. hostConfig.Memory = 0
  122. hostConfig.MemorySwap = -1
  123. }
  124. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !sysInfo.SwapLimit {
  125. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  126. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  127. hostConfig.MemorySwap = -1
  128. }
  129. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  130. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  131. }
  132. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  133. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  134. }
  135. if hostConfig.MemorySwappiness != nil && *hostConfig.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  136. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  137. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  138. hostConfig.MemorySwappiness = nil
  139. }
  140. if hostConfig.MemorySwappiness != nil {
  141. swappiness := *hostConfig.MemorySwappiness
  142. if swappiness < -1 || swappiness > 100 {
  143. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  144. }
  145. }
  146. if hostConfig.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  147. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  148. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  149. hostConfig.MemoryReservation = 0
  150. }
  151. if hostConfig.Memory > 0 && hostConfig.MemoryReservation > 0 && hostConfig.Memory < hostConfig.MemoryReservation {
  152. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage.")
  153. }
  154. if hostConfig.KernelMemory > 0 && !sysInfo.KernelMemory {
  155. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  156. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  157. hostConfig.KernelMemory = 0
  158. }
  159. if hostConfig.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  160. 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.")
  161. 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.")
  162. }
  163. if hostConfig.CPUShares > 0 && !sysInfo.CPUShares {
  164. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  165. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  166. hostConfig.CPUShares = 0
  167. }
  168. if hostConfig.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  169. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  170. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  171. hostConfig.CPUPeriod = 0
  172. }
  173. if hostConfig.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  174. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  175. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  176. hostConfig.CPUQuota = 0
  177. }
  178. if (hostConfig.CpusetCpus != "" || hostConfig.CpusetMems != "") && !sysInfo.Cpuset {
  179. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  180. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  181. hostConfig.CpusetCpus = ""
  182. hostConfig.CpusetMems = ""
  183. }
  184. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(hostConfig.CpusetCpus)
  185. if err != nil {
  186. return warnings, derr.ErrorCodeInvalidCpusetCpus.WithArgs(hostConfig.CpusetCpus)
  187. }
  188. if !cpusAvailable {
  189. return warnings, derr.ErrorCodeNotAvailableCpusetCpus.WithArgs(hostConfig.CpusetCpus, sysInfo.Cpus)
  190. }
  191. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(hostConfig.CpusetMems)
  192. if err != nil {
  193. return warnings, derr.ErrorCodeInvalidCpusetMems.WithArgs(hostConfig.CpusetMems)
  194. }
  195. if !memsAvailable {
  196. return warnings, derr.ErrorCodeNotAvailableCpusetMems.WithArgs(hostConfig.CpusetMems, sysInfo.Mems)
  197. }
  198. if hostConfig.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  199. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  200. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  201. hostConfig.BlkioWeight = 0
  202. }
  203. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  204. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  205. }
  206. if hostConfig.OomKillDisable && !sysInfo.OomKillDisable {
  207. hostConfig.OomKillDisable = false
  208. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  209. }
  210. if sysInfo.IPv4ForwardingDisabled {
  211. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  212. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  213. }
  214. return warnings, nil
  215. }
  216. // checkConfigOptions checks for mutually incompatible config options
  217. func checkConfigOptions(config *Config) error {
  218. // Check for mutually incompatible config options
  219. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  220. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  221. }
  222. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  223. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  224. }
  225. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  226. config.Bridge.EnableIPMasq = false
  227. }
  228. return nil
  229. }
  230. // checkSystem validates platform-specific requirements
  231. func checkSystem() error {
  232. if os.Geteuid() != 0 {
  233. return fmt.Errorf("The Docker daemon needs to be run as root")
  234. }
  235. return checkKernel()
  236. }
  237. // configureKernelSecuritySupport configures and validate security support for the kernel
  238. func configureKernelSecuritySupport(config *Config, driverName string) error {
  239. if config.EnableSelinuxSupport {
  240. if selinuxEnabled() {
  241. // As Docker on either btrfs or overlayFS and SELinux are incompatible at present, error on both being enabled
  242. if driverName == "btrfs" || driverName == "overlay" {
  243. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  244. }
  245. logrus.Debug("SELinux enabled successfully")
  246. } else {
  247. logrus.Warn("Docker could not enable SELinux on the host system")
  248. }
  249. } else {
  250. selinuxSetDisabled()
  251. }
  252. return nil
  253. }
  254. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  255. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  256. return migrateIfAufs(driver, root)
  257. }
  258. func configureSysInit(config *Config) (string, error) {
  259. localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  260. sysInitPath := utils.DockerInitPath(localCopy)
  261. if sysInitPath == "" {
  262. 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.")
  263. }
  264. if sysInitPath != localCopy {
  265. // 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).
  266. if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  267. return "", err
  268. }
  269. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  270. return "", err
  271. }
  272. if err := os.Chmod(localCopy, 0700); err != nil {
  273. return "", err
  274. }
  275. sysInitPath = localCopy
  276. }
  277. return sysInitPath, nil
  278. }
  279. func isBridgeNetworkDisabled(config *Config) bool {
  280. return config.Bridge.Iface == disableNetworkBridge
  281. }
  282. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  283. options := []nwconfig.Option{}
  284. if dconfig == nil {
  285. return options, nil
  286. }
  287. if strings.TrimSpace(dconfig.DefaultNetwork) != "" {
  288. dn := strings.Split(dconfig.DefaultNetwork, ":")
  289. if len(dn) < 2 {
  290. return nil, fmt.Errorf("default network daemon config must be of the form NETWORKDRIVER:NETWORKNAME")
  291. }
  292. options = append(options, nwconfig.OptionDefaultDriver(dn[0]))
  293. options = append(options, nwconfig.OptionDefaultNetwork(strings.Join(dn[1:], ":")))
  294. } else {
  295. dd := runconfig.DefaultDaemonNetworkMode()
  296. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  297. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  298. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  299. }
  300. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  301. kv := strings.Split(dconfig.ClusterStore, "://")
  302. if len(kv) < 2 {
  303. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  304. }
  305. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  306. options = append(options, nwconfig.OptionKVProviderURL(strings.Join(kv[1:], "://")))
  307. }
  308. if daemon.discoveryWatcher != nil {
  309. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  310. }
  311. if dconfig.ClusterAdvertise != "" {
  312. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  313. }
  314. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  315. options = append(options, driverOptions(dconfig)...)
  316. return options, nil
  317. }
  318. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  319. netOptions, err := daemon.networkOptions(config)
  320. if err != nil {
  321. return nil, err
  322. }
  323. controller, err := libnetwork.New(netOptions...)
  324. if err != nil {
  325. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  326. }
  327. // Initialize default network on "null"
  328. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  329. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  330. }
  331. // Initialize default network on "host"
  332. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  333. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  334. }
  335. if !config.DisableBridge {
  336. // Initialize default driver "bridge"
  337. if err := initBridgeDriver(controller, config); err != nil {
  338. return nil, err
  339. }
  340. }
  341. return controller, nil
  342. }
  343. func driverOptions(config *Config) []nwconfig.Option {
  344. bridgeConfig := options.Generic{
  345. "EnableIPForwarding": config.Bridge.EnableIPForward,
  346. "EnableIPTables": config.Bridge.EnableIPTables,
  347. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy}
  348. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  349. dOptions := []nwconfig.Option{}
  350. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  351. return dOptions
  352. }
  353. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  354. netOption := options.Generic{
  355. "BridgeName": config.Bridge.Iface,
  356. "DefaultBridge": true,
  357. "Mtu": config.Mtu,
  358. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  359. "EnableICC": config.Bridge.InterContainerCommunication,
  360. }
  361. if config.Bridge.IP != "" {
  362. ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
  363. if err != nil {
  364. return err
  365. }
  366. bipNet.IP = ip
  367. netOption["AddressIPv4"] = bipNet
  368. }
  369. if config.Bridge.FixedCIDR != "" {
  370. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  371. if err != nil {
  372. return err
  373. }
  374. netOption["FixedCIDR"] = fCIDR
  375. }
  376. if config.Bridge.FixedCIDRv6 != "" {
  377. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  378. if err != nil {
  379. return err
  380. }
  381. netOption["FixedCIDRv6"] = fCIDRv6
  382. }
  383. if config.Bridge.DefaultGatewayIPv4 != nil {
  384. netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
  385. }
  386. if config.Bridge.DefaultGatewayIPv6 != nil {
  387. netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
  388. }
  389. // --ip processing
  390. if config.Bridge.DefaultIP != nil {
  391. netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
  392. }
  393. // Initialize default network on "bridge" with the same name
  394. _, err := controller.NewNetwork("bridge", "bridge",
  395. libnetwork.NetworkOptionGeneric(options.Generic{
  396. netlabel.GenericData: netOption,
  397. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  398. }),
  399. libnetwork.NetworkOptionPersist(false))
  400. if err != nil {
  401. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  402. }
  403. return nil
  404. }
  405. // setupInitLayer populates a directory with mountpoints suitable
  406. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  407. // empty file at /.dockerinit
  408. //
  409. // This extra layer is used by all containers as the top-most ro layer. It protects
  410. // the container from unwanted side-effects on the rw layer.
  411. func setupInitLayer(initLayer string) error {
  412. for pth, typ := range map[string]string{
  413. "/dev/pts": "dir",
  414. "/dev/shm": "dir",
  415. "/proc": "dir",
  416. "/sys": "dir",
  417. "/.dockerinit": "file",
  418. "/.dockerenv": "file",
  419. "/etc/resolv.conf": "file",
  420. "/etc/hosts": "file",
  421. "/etc/hostname": "file",
  422. "/dev/console": "file",
  423. "/etc/mtab": "/proc/mounts",
  424. } {
  425. parts := strings.Split(pth, "/")
  426. prev := "/"
  427. for _, p := range parts[1:] {
  428. prev = filepath.Join(prev, p)
  429. syscall.Unlink(filepath.Join(initLayer, prev))
  430. }
  431. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  432. if os.IsNotExist(err) {
  433. if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil {
  434. return err
  435. }
  436. switch typ {
  437. case "dir":
  438. if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil {
  439. return err
  440. }
  441. case "file":
  442. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  443. if err != nil {
  444. return err
  445. }
  446. f.Close()
  447. default:
  448. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  449. return err
  450. }
  451. }
  452. } else {
  453. return err
  454. }
  455. }
  456. }
  457. // Layer is ready to use, if it wasn't before.
  458. return nil
  459. }
  460. // registerLinks writes the links to a file.
  461. func (daemon *Daemon) registerLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  462. if hostConfig == nil || hostConfig.Links == nil {
  463. return nil
  464. }
  465. for _, l := range hostConfig.Links {
  466. name, alias, err := parsers.ParseLink(l)
  467. if err != nil {
  468. return err
  469. }
  470. child, err := daemon.Get(name)
  471. if err != nil {
  472. //An error from daemon.Get() means this name could not be found
  473. return fmt.Errorf("Could not get container for %s", name)
  474. }
  475. for child.hostConfig.NetworkMode.IsContainer() {
  476. parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
  477. child, err = daemon.Get(parts[1])
  478. if err != nil {
  479. return fmt.Errorf("Could not get container for %s", parts[1])
  480. }
  481. }
  482. if child.hostConfig.NetworkMode.IsHost() {
  483. return runconfig.ErrConflictHostNetworkAndLinks
  484. }
  485. if err := daemon.registerLink(container, child, alias); err != nil {
  486. return err
  487. }
  488. }
  489. // After we load all the links into the daemon
  490. // set them to nil on the hostconfig
  491. hostConfig.Links = nil
  492. if err := container.writeHostConfig(); err != nil {
  493. return err
  494. }
  495. return nil
  496. }
  497. func (daemon *Daemon) newBaseContainer(id string) Container {
  498. return Container{
  499. CommonContainer: CommonContainer{
  500. ID: id,
  501. State: NewState(),
  502. execCommands: newExecStore(),
  503. root: daemon.containerRoot(id),
  504. },
  505. MountPoints: make(map[string]*mountPoint),
  506. Volumes: make(map[string]string),
  507. VolumesRW: make(map[string]bool),
  508. }
  509. }
  510. // getDefaultRouteMtu returns the MTU for the default route's interface.
  511. func getDefaultRouteMtu() (int, error) {
  512. routes, err := netlink.RouteList(nil, 0)
  513. if err != nil {
  514. return 0, err
  515. }
  516. for _, r := range routes {
  517. // a nil Dst means that this is the default route.
  518. if r.Dst == nil {
  519. i, err := net.InterfaceByIndex(r.LinkIndex)
  520. if err != nil {
  521. continue
  522. }
  523. return i.MTU, nil
  524. }
  525. }
  526. return 0, errNoDefaultRoute
  527. }