daemon_unix.go 21 KB

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