daemon_unix.go 18 KB

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