daemon_unix.go 17 KB

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