daemon_unix.go 18 KB

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