daemon_unix.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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: %q", portStr)
  120. }
  121. for _, pb := range hostConfig.PortBindings[port] {
  122. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  123. if err != nil {
  124. return warnings, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  125. }
  126. }
  127. }
  128. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  129. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  130. }
  131. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  132. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  133. }
  134. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  135. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  136. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  137. hostConfig.Memory = 0
  138. }
  139. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  140. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  141. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  142. hostConfig.MemorySwap = -1
  143. }
  144. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  145. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  146. }
  147. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  148. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  149. }
  150. if hostConfig.MemorySwappiness != -1 && !daemon.SystemConfig().MemorySwappiness {
  151. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  152. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  153. hostConfig.MemorySwappiness = -1
  154. }
  155. if hostConfig.MemorySwappiness != -1 && (hostConfig.MemorySwappiness < 0 || hostConfig.MemorySwappiness > 100) {
  156. return warnings, fmt.Errorf("Invalid value: %d, valid memory swappiness range is 0-100.", hostConfig.MemorySwappiness)
  157. }
  158. if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  159. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  160. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  161. hostConfig.CpuPeriod = 0
  162. }
  163. if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  164. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  165. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  166. hostConfig.CpuQuota = 0
  167. }
  168. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  169. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  170. }
  171. if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  172. hostConfig.OomKillDisable = false
  173. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  174. }
  175. if daemon.SystemConfig().IPv4ForwardingDisabled {
  176. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  177. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  178. }
  179. return warnings, nil
  180. }
  181. // checkConfigOptions checks for mutually incompatible config options
  182. func checkConfigOptions(config *Config) error {
  183. // Check for mutually incompatible config options
  184. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  185. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  186. }
  187. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  188. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  189. }
  190. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  191. config.Bridge.EnableIPMasq = false
  192. }
  193. return nil
  194. }
  195. // checkSystem validates platform-specific requirements
  196. func checkSystem() error {
  197. if os.Geteuid() != 0 {
  198. return fmt.Errorf("The Docker daemon needs to be run as root")
  199. }
  200. if err := checkKernel(); err != nil {
  201. return err
  202. }
  203. return nil
  204. }
  205. // configureKernelSecuritySupport configures and validate security support for the kernel
  206. func configureKernelSecuritySupport(config *Config, driverName string) error {
  207. if config.EnableSelinuxSupport {
  208. if selinuxEnabled() {
  209. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  210. if driverName == "btrfs" {
  211. return fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  212. }
  213. logrus.Debug("SELinux enabled successfully")
  214. } else {
  215. logrus.Warn("Docker could not enable SELinux on the host system")
  216. }
  217. } else {
  218. selinuxSetDisabled()
  219. }
  220. return nil
  221. }
  222. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  223. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  224. return migrateIfAufs(driver, root)
  225. }
  226. func configureVolumes(config *Config) error {
  227. volumesDriver, err := local.New(config.Root)
  228. if err != nil {
  229. return err
  230. }
  231. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  232. return nil
  233. }
  234. func configureSysInit(config *Config) (string, error) {
  235. localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  236. sysInitPath := utils.DockerInitPath(localCopy)
  237. if sysInitPath == "" {
  238. 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.")
  239. }
  240. if sysInitPath != localCopy {
  241. // 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).
  242. if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  243. return "", err
  244. }
  245. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  246. return "", err
  247. }
  248. if err := os.Chmod(localCopy, 0700); err != nil {
  249. return "", err
  250. }
  251. sysInitPath = localCopy
  252. }
  253. return sysInitPath, nil
  254. }
  255. func isBridgeNetworkDisabled(config *Config) bool {
  256. return config.Bridge.Iface == disableNetworkBridge
  257. }
  258. func networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  259. options := []nwconfig.Option{}
  260. if dconfig == nil {
  261. return options, nil
  262. }
  263. if strings.TrimSpace(dconfig.DefaultNetwork) != "" {
  264. dn := strings.Split(dconfig.DefaultNetwork, ":")
  265. if len(dn) < 2 {
  266. return nil, fmt.Errorf("default network daemon config must be of the form NETWORKDRIVER:NETWORKNAME")
  267. }
  268. options = append(options, nwconfig.OptionDefaultDriver(dn[0]))
  269. options = append(options, nwconfig.OptionDefaultNetwork(strings.Join(dn[1:], ":")))
  270. } else {
  271. dd := runconfig.DefaultDaemonNetworkMode()
  272. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  273. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  274. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  275. }
  276. if strings.TrimSpace(dconfig.NetworkKVStore) != "" {
  277. kv := strings.Split(dconfig.NetworkKVStore, ":")
  278. if len(kv) < 2 {
  279. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER:KV-URL")
  280. }
  281. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  282. options = append(options, nwconfig.OptionKVProviderURL(strings.Join(kv[1:], ":")))
  283. }
  284. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  285. return options, nil
  286. }
  287. func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  288. netOptions, err := networkOptions(config)
  289. if err != nil {
  290. return nil, err
  291. }
  292. controller, err := libnetwork.New(netOptions...)
  293. if err != nil {
  294. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  295. }
  296. // Initialize default driver "null"
  297. if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
  298. return nil, fmt.Errorf("Error initializing null driver: %v", err)
  299. }
  300. // Initialize default network on "null"
  301. if _, err := controller.NewNetwork("null", "none"); err != nil {
  302. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  303. }
  304. // Initialize default driver "host"
  305. if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
  306. return nil, fmt.Errorf("Error initializing host driver: %v", err)
  307. }
  308. // Initialize default network on "host"
  309. if _, err := controller.NewNetwork("host", "host"); err != nil {
  310. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  311. }
  312. if !config.DisableBridge {
  313. // Initialize default driver "bridge"
  314. if err := initBridgeDriver(controller, config); err != nil {
  315. return nil, err
  316. }
  317. }
  318. return controller, nil
  319. }
  320. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  321. option := options.Generic{
  322. "EnableIPForwarding": config.Bridge.EnableIPForward}
  323. if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
  324. return fmt.Errorf("Error initializing bridge driver: %v", err)
  325. }
  326. netOption := options.Generic{
  327. "BridgeName": config.Bridge.Iface,
  328. "Mtu": config.Mtu,
  329. "EnableIPTables": config.Bridge.EnableIPTables,
  330. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  331. "EnableICC": config.Bridge.InterContainerCommunication,
  332. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
  333. }
  334. if config.Bridge.IP != "" {
  335. ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
  336. if err != nil {
  337. return err
  338. }
  339. bipNet.IP = ip
  340. netOption["AddressIPv4"] = bipNet
  341. }
  342. if config.Bridge.FixedCIDR != "" {
  343. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  344. if err != nil {
  345. return err
  346. }
  347. netOption["FixedCIDR"] = fCIDR
  348. }
  349. if config.Bridge.FixedCIDRv6 != "" {
  350. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  351. if err != nil {
  352. return err
  353. }
  354. netOption["FixedCIDRv6"] = fCIDRv6
  355. }
  356. if config.Bridge.DefaultGatewayIPv4 != nil {
  357. netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
  358. }
  359. if config.Bridge.DefaultGatewayIPv6 != nil {
  360. netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
  361. }
  362. // --ip processing
  363. if config.Bridge.DefaultIP != nil {
  364. netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
  365. }
  366. // Initialize default network on "bridge" with the same name
  367. _, err := controller.NewNetwork("bridge", "bridge",
  368. libnetwork.NetworkOptionGeneric(options.Generic{
  369. netlabel.GenericData: netOption,
  370. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  371. }))
  372. if err != nil {
  373. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  374. }
  375. return nil
  376. }
  377. // setupInitLayer populates a directory with mountpoints suitable
  378. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  379. // empty file at /.dockerinit
  380. //
  381. // This extra layer is used by all containers as the top-most ro layer. It protects
  382. // the container from unwanted side-effects on the rw layer.
  383. func setupInitLayer(initLayer string) error {
  384. for pth, typ := range map[string]string{
  385. "/dev/pts": "dir",
  386. "/dev/shm": "dir",
  387. "/proc": "dir",
  388. "/sys": "dir",
  389. "/.dockerinit": "file",
  390. "/.dockerenv": "file",
  391. "/etc/resolv.conf": "file",
  392. "/etc/hosts": "file",
  393. "/etc/hostname": "file",
  394. "/dev/console": "file",
  395. "/etc/mtab": "/proc/mounts",
  396. } {
  397. parts := strings.Split(pth, "/")
  398. prev := "/"
  399. for _, p := range parts[1:] {
  400. prev = filepath.Join(prev, p)
  401. syscall.Unlink(filepath.Join(initLayer, prev))
  402. }
  403. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  404. if os.IsNotExist(err) {
  405. if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil {
  406. return err
  407. }
  408. switch typ {
  409. case "dir":
  410. if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil {
  411. return err
  412. }
  413. case "file":
  414. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  415. if err != nil {
  416. return err
  417. }
  418. f.Close()
  419. default:
  420. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  421. return err
  422. }
  423. }
  424. } else {
  425. return err
  426. }
  427. }
  428. }
  429. // Layer is ready to use, if it wasn't before.
  430. return nil
  431. }
  432. func (daemon *Daemon) NetworkApiRouter() func(w http.ResponseWriter, req *http.Request) {
  433. return nwapi.NewHTTPHandler(daemon.netController)
  434. }
  435. func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  436. if hostConfig == nil || hostConfig.Links == nil {
  437. return nil
  438. }
  439. for _, l := range hostConfig.Links {
  440. name, alias, err := parsers.ParseLink(l)
  441. if err != nil {
  442. return err
  443. }
  444. child, err := daemon.Get(name)
  445. if err != nil {
  446. //An error from daemon.Get() means this name could not be found
  447. return fmt.Errorf("Could not get container for %s", name)
  448. }
  449. for child.hostConfig.NetworkMode.IsContainer() {
  450. parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
  451. child, err = daemon.Get(parts[1])
  452. if err != nil {
  453. return fmt.Errorf("Could not get container for %s", parts[1])
  454. }
  455. }
  456. if child.hostConfig.NetworkMode.IsHost() {
  457. return runconfig.ErrConflictHostNetworkAndLinks
  458. }
  459. if err := daemon.RegisterLink(container, child, alias); err != nil {
  460. return err
  461. }
  462. }
  463. // After we load all the links into the daemon
  464. // set them to nil on the hostconfig
  465. hostConfig.Links = nil
  466. if err := container.WriteHostConfig(); err != nil {
  467. return err
  468. }
  469. return nil
  470. }