daemon_unix.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // +build !windows
  2. package daemon
  3. import (
  4. "fmt"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/docker/autogen/dockerversion"
  12. "github.com/docker/docker/daemon/graphdriver"
  13. "github.com/docker/docker/graph"
  14. "github.com/docker/docker/pkg/archive"
  15. "github.com/docker/docker/pkg/fileutils"
  16. "github.com/docker/docker/pkg/parsers/kernel"
  17. "github.com/docker/docker/runconfig"
  18. "github.com/docker/docker/utils"
  19. volumedrivers "github.com/docker/docker/volume/drivers"
  20. "github.com/docker/docker/volume/local"
  21. "github.com/docker/libcontainer/label"
  22. "github.com/docker/libnetwork"
  23. "github.com/docker/libnetwork/netlabel"
  24. "github.com/docker/libnetwork/options"
  25. )
  26. const runDir = "/var/run/docker"
  27. const defaultVolumesPathName = "volumes"
  28. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  29. initID := fmt.Sprintf("%s-init", container.ID)
  30. return daemon.driver.Changes(container.ID, initID)
  31. }
  32. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  33. initID := fmt.Sprintf("%s-init", container.ID)
  34. return daemon.driver.Diff(container.ID, initID)
  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 (daemon *Daemon) createRootfs(container *Container) error {
  59. // Step 1: create the container directory.
  60. // This doubles as a barrier to avoid race conditions.
  61. if err := os.Mkdir(container.root, 0700); err != nil {
  62. return err
  63. }
  64. initID := fmt.Sprintf("%s-init", container.ID)
  65. if err := daemon.driver.Create(initID, container.ImageID); err != nil {
  66. return err
  67. }
  68. initPath, err := daemon.driver.Get(initID, "")
  69. if err != nil {
  70. return err
  71. }
  72. defer daemon.driver.Put(initID)
  73. if err := graph.SetupInitLayer(initPath); err != nil {
  74. return err
  75. }
  76. if err := daemon.driver.Create(container.ID, initID); err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. func checkKernel() error {
  82. // Check for unsupported kernel versions
  83. // FIXME: it would be cleaner to not test for specific versions, but rather
  84. // test for specific functionalities.
  85. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  86. // without actually causing a kernel panic, so we need this workaround until
  87. // the circumstances of pre-3.10 crashes are clearer.
  88. // For details see https://github.com/docker/docker/issues/407
  89. if k, err := kernel.GetKernelVersion(); err != nil {
  90. logrus.Warnf("%s", err)
  91. } else {
  92. if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 {
  93. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  94. 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())
  95. }
  96. }
  97. }
  98. return nil
  99. }
  100. func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  101. var warnings []string
  102. if config != nil {
  103. // The check for a valid workdir path is made on the server rather than in the
  104. // client. This is because we don't know the type of path (Linux or Windows)
  105. // to validate on the client.
  106. if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) {
  107. return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir)
  108. }
  109. }
  110. if hostConfig == nil {
  111. return warnings, nil
  112. }
  113. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  114. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  115. }
  116. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  117. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  118. }
  119. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  120. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  121. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  122. hostConfig.Memory = 0
  123. }
  124. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  125. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  126. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  127. hostConfig.MemorySwap = -1
  128. }
  129. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  130. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  131. }
  132. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  133. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  134. }
  135. if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  136. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  137. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  138. hostConfig.CpuPeriod = 0
  139. }
  140. if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  141. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  142. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  143. hostConfig.CpuQuota = 0
  144. }
  145. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  146. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  147. }
  148. if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  149. hostConfig.OomKillDisable = false
  150. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  151. }
  152. if daemon.SystemConfig().IPv4ForwardingDisabled {
  153. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  154. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  155. }
  156. return warnings, nil
  157. }
  158. // checkConfigOptions checks for mutually incompatible config options
  159. func checkConfigOptions(config *Config) error {
  160. // Check for mutually incompatible config options
  161. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  162. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  163. }
  164. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  165. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  166. }
  167. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  168. config.Bridge.EnableIPMasq = false
  169. }
  170. return nil
  171. }
  172. // checkSystem validates the system is supported and we have sufficient privileges
  173. func checkSystem() error {
  174. // TODO Windows. Once daemon is running on Windows, move this code back to
  175. // NewDaemon() in daemon.go, and extend the check to support Windows.
  176. if runtime.GOOS != "linux" {
  177. return ErrSystemNotSupported
  178. }
  179. if os.Geteuid() != 0 {
  180. return fmt.Errorf("The Docker daemon needs to be run as root")
  181. }
  182. if err := checkKernel(); err != nil {
  183. return err
  184. }
  185. return nil
  186. }
  187. // configureKernelSecuritySupport configures and validate security support for the kernel
  188. func configureKernelSecuritySupport(config *Config, driverName string) error {
  189. if config.EnableSelinuxSupport {
  190. if selinuxEnabled() {
  191. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  192. if driverName == "btrfs" {
  193. return fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  194. }
  195. logrus.Debug("SELinux enabled successfully")
  196. } else {
  197. logrus.Warn("Docker could not enable SELinux on the host system")
  198. }
  199. } else {
  200. selinuxSetDisabled()
  201. }
  202. return nil
  203. }
  204. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  205. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  206. return migrateIfAufs(driver, root)
  207. }
  208. func configureVolumes(config *Config) error {
  209. volumesDriver, err := local.New(config.Root)
  210. if err != nil {
  211. return err
  212. }
  213. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  214. return nil
  215. }
  216. func configureSysInit(config *Config) (string, error) {
  217. localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  218. sysInitPath := utils.DockerInitPath(localCopy)
  219. if sysInitPath == "" {
  220. 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.")
  221. }
  222. if sysInitPath != localCopy {
  223. // 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).
  224. if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  225. return "", err
  226. }
  227. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  228. return "", err
  229. }
  230. if err := os.Chmod(localCopy, 0700); err != nil {
  231. return "", err
  232. }
  233. sysInitPath = localCopy
  234. }
  235. return sysInitPath, nil
  236. }
  237. func isNetworkDisabled(config *Config) bool {
  238. return config.Bridge.Iface == disableNetworkBridge
  239. }
  240. func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  241. controller, err := libnetwork.New()
  242. if err != nil {
  243. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  244. }
  245. // Initialize default driver "null"
  246. if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
  247. return nil, fmt.Errorf("Error initializing null driver: %v", err)
  248. }
  249. // Initialize default network on "null"
  250. if _, err := controller.NewNetwork("null", "none"); err != nil {
  251. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  252. }
  253. // Initialize default driver "host"
  254. if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
  255. return nil, fmt.Errorf("Error initializing host driver: %v", err)
  256. }
  257. // Initialize default network on "host"
  258. if _, err := controller.NewNetwork("host", "host"); err != nil {
  259. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  260. }
  261. // Initialize default driver "bridge"
  262. option := options.Generic{
  263. "EnableIPForwarding": config.Bridge.EnableIPForward}
  264. if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
  265. return nil, fmt.Errorf("Error initializing bridge driver: %v", err)
  266. }
  267. netOption := options.Generic{
  268. "BridgeName": config.Bridge.Iface,
  269. "Mtu": config.Mtu,
  270. "EnableIPTables": config.Bridge.EnableIPTables,
  271. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  272. "EnableICC": config.Bridge.InterContainerCommunication,
  273. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
  274. }
  275. if config.Bridge.IP != "" {
  276. ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
  277. if err != nil {
  278. return nil, err
  279. }
  280. bipNet.IP = ip
  281. netOption["AddressIPv4"] = bipNet
  282. }
  283. if config.Bridge.FixedCIDR != "" {
  284. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  285. if err != nil {
  286. return nil, err
  287. }
  288. netOption["FixedCIDR"] = fCIDR
  289. }
  290. if config.Bridge.FixedCIDRv6 != "" {
  291. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  292. if err != nil {
  293. return nil, err
  294. }
  295. netOption["FixedCIDRv6"] = fCIDRv6
  296. }
  297. if config.Bridge.DefaultGatewayIPv4 != nil {
  298. netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
  299. }
  300. if config.Bridge.DefaultGatewayIPv6 != nil {
  301. netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
  302. }
  303. // --ip processing
  304. if config.Bridge.DefaultIP != nil {
  305. netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
  306. }
  307. // Initialize default network on "bridge" with the same name
  308. _, err = controller.NewNetwork("bridge", "bridge",
  309. libnetwork.NetworkOptionGeneric(options.Generic{
  310. netlabel.GenericData: netOption,
  311. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  312. }))
  313. if err != nil {
  314. return nil, fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  315. }
  316. return controller, nil
  317. }