daemon_unix.go 17 KB

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