daemon_unix.go 15 KB

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