daemon_unix.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "runtime/debug"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/docker/docker/api/types"
  17. "github.com/docker/docker/api/types/blkiodev"
  18. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  19. containertypes "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/container"
  21. "github.com/docker/docker/daemon/config"
  22. "github.com/docker/docker/image"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/idtools"
  25. "github.com/docker/docker/pkg/parsers"
  26. "github.com/docker/docker/pkg/parsers/kernel"
  27. "github.com/docker/docker/pkg/sysinfo"
  28. "github.com/docker/docker/runconfig"
  29. "github.com/docker/docker/volume"
  30. "github.com/docker/libnetwork"
  31. nwconfig "github.com/docker/libnetwork/config"
  32. "github.com/docker/libnetwork/drivers/bridge"
  33. "github.com/docker/libnetwork/netlabel"
  34. "github.com/docker/libnetwork/netutils"
  35. "github.com/docker/libnetwork/options"
  36. lntypes "github.com/docker/libnetwork/types"
  37. "github.com/golang/protobuf/ptypes"
  38. "github.com/opencontainers/runc/libcontainer/cgroups"
  39. rsystem "github.com/opencontainers/runc/libcontainer/system"
  40. specs "github.com/opencontainers/runtime-spec/specs-go"
  41. "github.com/opencontainers/selinux/go-selinux/label"
  42. "github.com/pkg/errors"
  43. "github.com/sirupsen/logrus"
  44. "github.com/vishvananda/netlink"
  45. "golang.org/x/sys/unix"
  46. )
  47. const (
  48. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  49. linuxMinCPUShares = 2
  50. linuxMaxCPUShares = 262144
  51. platformSupported = true
  52. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  53. linuxMinMemory = 4194304
  54. // constants for remapped root settings
  55. defaultIDSpecifier string = "default"
  56. defaultRemappedID string = "dockremap"
  57. // constant for cgroup drivers
  58. cgroupFsDriver = "cgroupfs"
  59. cgroupSystemdDriver = "systemd"
  60. )
  61. type containerGetter interface {
  62. GetContainer(string) (*container.Container, error)
  63. }
  64. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  65. memory := specs.LinuxMemory{}
  66. if config.Memory > 0 {
  67. memory.Limit = &config.Memory
  68. }
  69. if config.MemoryReservation > 0 {
  70. memory.Reservation = &config.MemoryReservation
  71. }
  72. if config.MemorySwap > 0 {
  73. memory.Swap = &config.MemorySwap
  74. }
  75. if config.MemorySwappiness != nil {
  76. swappiness := uint64(*config.MemorySwappiness)
  77. memory.Swappiness = &swappiness
  78. }
  79. if config.KernelMemory != 0 {
  80. memory.Kernel = &config.KernelMemory
  81. }
  82. return &memory
  83. }
  84. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  85. cpu := specs.LinuxCPU{}
  86. if config.CPUShares < 0 {
  87. return nil, fmt.Errorf("shares: invalid argument")
  88. }
  89. if config.CPUShares >= 0 {
  90. shares := uint64(config.CPUShares)
  91. cpu.Shares = &shares
  92. }
  93. if config.CpusetCpus != "" {
  94. cpu.Cpus = config.CpusetCpus
  95. }
  96. if config.CpusetMems != "" {
  97. cpu.Mems = config.CpusetMems
  98. }
  99. if config.NanoCPUs > 0 {
  100. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  101. period := uint64(100 * time.Millisecond / time.Microsecond)
  102. quota := config.NanoCPUs * int64(period) / 1e9
  103. cpu.Period = &period
  104. cpu.Quota = &quota
  105. }
  106. if config.CPUPeriod != 0 {
  107. period := uint64(config.CPUPeriod)
  108. cpu.Period = &period
  109. }
  110. if config.CPUQuota != 0 {
  111. q := config.CPUQuota
  112. cpu.Quota = &q
  113. }
  114. if config.CPURealtimePeriod != 0 {
  115. period := uint64(config.CPURealtimePeriod)
  116. cpu.RealtimePeriod = &period
  117. }
  118. if config.CPURealtimeRuntime != 0 {
  119. c := config.CPURealtimeRuntime
  120. cpu.RealtimeRuntime = &c
  121. }
  122. return &cpu, nil
  123. }
  124. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  125. var stat unix.Stat_t
  126. var blkioWeightDevices []specs.LinuxWeightDevice
  127. for _, weightDevice := range config.BlkioWeightDevice {
  128. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  129. return nil, err
  130. }
  131. weight := weightDevice.Weight
  132. d := specs.LinuxWeightDevice{Weight: &weight}
  133. d.Major = int64(stat.Rdev / 256)
  134. d.Minor = int64(stat.Rdev % 256)
  135. blkioWeightDevices = append(blkioWeightDevices, d)
  136. }
  137. return blkioWeightDevices, nil
  138. }
  139. func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfig *containertypes.HostConfig) error {
  140. container.NoNewPrivileges = daemon.configStore.NoNewPrivileges
  141. return parseSecurityOpt(container, hostConfig)
  142. }
  143. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  144. var (
  145. labelOpts []string
  146. err error
  147. )
  148. for _, opt := range config.SecurityOpt {
  149. if opt == "no-new-privileges" {
  150. container.NoNewPrivileges = true
  151. continue
  152. }
  153. if opt == "disable" {
  154. labelOpts = append(labelOpts, "disable")
  155. continue
  156. }
  157. var con []string
  158. if strings.Contains(opt, "=") {
  159. con = strings.SplitN(opt, "=", 2)
  160. } else if strings.Contains(opt, ":") {
  161. con = strings.SplitN(opt, ":", 2)
  162. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  163. }
  164. if len(con) != 2 {
  165. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  166. }
  167. switch con[0] {
  168. case "label":
  169. labelOpts = append(labelOpts, con[1])
  170. case "apparmor":
  171. container.AppArmorProfile = con[1]
  172. case "seccomp":
  173. container.SeccompProfile = con[1]
  174. case "no-new-privileges":
  175. noNewPrivileges, err := strconv.ParseBool(con[1])
  176. if err != nil {
  177. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  178. }
  179. container.NoNewPrivileges = noNewPrivileges
  180. default:
  181. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  182. }
  183. }
  184. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  185. return err
  186. }
  187. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.LinuxThrottleDevice, error) {
  188. var throttleDevices []specs.LinuxThrottleDevice
  189. var stat unix.Stat_t
  190. for _, d := range devs {
  191. if err := unix.Stat(d.Path, &stat); err != nil {
  192. return nil, err
  193. }
  194. d := specs.LinuxThrottleDevice{Rate: d.Rate}
  195. d.Major = int64(stat.Rdev / 256)
  196. d.Minor = int64(stat.Rdev % 256)
  197. throttleDevices = append(throttleDevices, d)
  198. }
  199. return throttleDevices, nil
  200. }
  201. func checkKernel() error {
  202. // Check for unsupported kernel versions
  203. // FIXME: it would be cleaner to not test for specific versions, but rather
  204. // test for specific functionalities.
  205. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  206. // without actually causing a kernel panic, so we need this workaround until
  207. // the circumstances of pre-3.10 crashes are clearer.
  208. // For details see https://github.com/docker/docker/issues/407
  209. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  210. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  211. if !kernel.CheckKernelVersion(3, 10, 0) {
  212. v, _ := kernel.GetKernelVersion()
  213. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  214. logrus.Fatalf("Your Linux kernel version %s is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.", v.String())
  215. }
  216. }
  217. return nil
  218. }
  219. // adaptContainerSettings is called during container creation to modify any
  220. // settings necessary in the HostConfig structure.
  221. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  222. if adjustCPUShares && hostConfig.CPUShares > 0 {
  223. // Handle unsupported CPUShares
  224. if hostConfig.CPUShares < linuxMinCPUShares {
  225. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  226. hostConfig.CPUShares = linuxMinCPUShares
  227. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  228. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  229. hostConfig.CPUShares = linuxMaxCPUShares
  230. }
  231. }
  232. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  233. // By default, MemorySwap is set to twice the size of Memory.
  234. hostConfig.MemorySwap = hostConfig.Memory * 2
  235. }
  236. if hostConfig.ShmSize == 0 {
  237. hostConfig.ShmSize = config.DefaultShmSize
  238. if daemon.configStore != nil {
  239. hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
  240. }
  241. }
  242. // Set default IPC mode, if unset for container
  243. if hostConfig.IpcMode.IsEmpty() {
  244. m := config.DefaultIpcMode
  245. if daemon.configStore != nil {
  246. m = daemon.configStore.IpcMode
  247. }
  248. hostConfig.IpcMode = containertypes.IpcMode(m)
  249. }
  250. adaptSharedNamespaceContainer(daemon, hostConfig)
  251. var err error
  252. opts, err := daemon.generateSecurityOpt(hostConfig)
  253. if err != nil {
  254. return err
  255. }
  256. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, opts...)
  257. if hostConfig.OomKillDisable == nil {
  258. defaultOomKillDisable := false
  259. hostConfig.OomKillDisable = &defaultOomKillDisable
  260. }
  261. return nil
  262. }
  263. // adaptSharedNamespaceContainer replaces container name with its ID in hostConfig.
  264. // To be more precisely, it modifies `container:name` to `container:ID` of PidMode, IpcMode
  265. // and NetworkMode.
  266. //
  267. // When a container shares its namespace with another container, use ID can keep the namespace
  268. // sharing connection between the two containers even the another container is renamed.
  269. func adaptSharedNamespaceContainer(daemon containerGetter, hostConfig *containertypes.HostConfig) {
  270. containerPrefix := "container:"
  271. if hostConfig.PidMode.IsContainer() {
  272. pidContainer := hostConfig.PidMode.Container()
  273. // if there is any error returned here, we just ignore it and leave it to be
  274. // handled in the following logic
  275. if c, err := daemon.GetContainer(pidContainer); err == nil {
  276. hostConfig.PidMode = containertypes.PidMode(containerPrefix + c.ID)
  277. }
  278. }
  279. if hostConfig.IpcMode.IsContainer() {
  280. ipcContainer := hostConfig.IpcMode.Container()
  281. if c, err := daemon.GetContainer(ipcContainer); err == nil {
  282. hostConfig.IpcMode = containertypes.IpcMode(containerPrefix + c.ID)
  283. }
  284. }
  285. if hostConfig.NetworkMode.IsContainer() {
  286. netContainer := hostConfig.NetworkMode.ConnectedContainer()
  287. if c, err := daemon.GetContainer(netContainer); err == nil {
  288. hostConfig.NetworkMode = containertypes.NetworkMode(containerPrefix + c.ID)
  289. }
  290. }
  291. }
  292. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  293. warnings := []string{}
  294. fixMemorySwappiness(resources)
  295. // memory subsystem checks and adjustments
  296. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  297. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  298. }
  299. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  300. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  301. logrus.Warn("Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  302. resources.Memory = 0
  303. resources.MemorySwap = -1
  304. }
  305. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  306. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  307. logrus.Warn("Your kernel does not support swap limit capabilities,or the cgroup is not mounted. Memory limited without swap.")
  308. resources.MemorySwap = -1
  309. }
  310. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  311. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  312. }
  313. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  314. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  315. }
  316. if resources.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
  317. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  318. logrus.Warn("Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.")
  319. resources.MemorySwappiness = nil
  320. }
  321. if resources.MemorySwappiness != nil {
  322. swappiness := *resources.MemorySwappiness
  323. if swappiness < 0 || swappiness > 100 {
  324. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  325. }
  326. }
  327. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  328. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  329. logrus.Warn("Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  330. resources.MemoryReservation = 0
  331. }
  332. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  333. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  334. }
  335. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  336. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  337. }
  338. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  339. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  340. logrus.Warn("Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  341. resources.KernelMemory = 0
  342. }
  343. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  344. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  345. }
  346. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  347. warnings = append(warnings, "You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  348. logrus.Warn("You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  349. }
  350. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  351. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  352. // warning the caller if they already wanted the feature to be off
  353. if *resources.OomKillDisable {
  354. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  355. logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  356. }
  357. resources.OomKillDisable = nil
  358. }
  359. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  360. warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  361. logrus.Warn("Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  362. resources.PidsLimit = 0
  363. }
  364. // cpu subsystem checks and adjustments
  365. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  366. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  367. }
  368. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  369. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  370. }
  371. if resources.NanoCPUs > 0 && (!sysInfo.CPUCfsPeriod || !sysInfo.CPUCfsQuota) {
  372. return warnings, fmt.Errorf("NanoCPUs can not be set, as your kernel does not support CPU cfs period/quota or the cgroup is not mounted")
  373. }
  374. // The highest precision we could get on Linux is 0.001, by setting
  375. // cpu.cfs_period_us=1000ms
  376. // cpu.cfs_quota=1ms
  377. // See the following link for details:
  378. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  379. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  380. // The error message is 0.01 so that this is consistent with Windows
  381. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  382. return warnings, fmt.Errorf("Range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU())
  383. }
  384. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  385. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  386. logrus.Warn("Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  387. resources.CPUShares = 0
  388. }
  389. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  390. warnings = append(warnings, "Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  391. logrus.Warn("Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  392. resources.CPUPeriod = 0
  393. }
  394. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  395. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  396. }
  397. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  398. warnings = append(warnings, "Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  399. logrus.Warn("Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  400. resources.CPUQuota = 0
  401. }
  402. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  403. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  404. }
  405. if resources.CPUPercent > 0 {
  406. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  407. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  408. resources.CPUPercent = 0
  409. }
  410. // cpuset subsystem checks and adjustments
  411. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  412. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  413. logrus.Warn("Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  414. resources.CpusetCpus = ""
  415. resources.CpusetMems = ""
  416. }
  417. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  418. if err != nil {
  419. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  420. }
  421. if !cpusAvailable {
  422. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  423. }
  424. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  425. if err != nil {
  426. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  427. }
  428. if !memsAvailable {
  429. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  430. }
  431. // blkio subsystem checks and adjustments
  432. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  433. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  434. logrus.Warn("Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  435. resources.BlkioWeight = 0
  436. }
  437. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  438. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  439. }
  440. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  441. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  442. }
  443. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  444. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  445. logrus.Warn("Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  446. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  447. }
  448. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  449. warnings = append(warnings, "Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded.")
  450. logrus.Warn("Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded")
  451. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  452. }
  453. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  454. warnings = append(warnings, "Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  455. logrus.Warn("Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  456. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  457. }
  458. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  459. warnings = append(warnings, "Your kernel does not support IOPS Block read limit or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  460. logrus.Warn("Your kernel does not support IOPS Block I/O read limit in IO or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  461. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  462. }
  463. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  464. warnings = append(warnings, "Your kernel does not support IOPS Block write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  465. logrus.Warn("Your kernel does not support IOPS Block I/O write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  466. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  467. }
  468. return warnings, nil
  469. }
  470. func (daemon *Daemon) getCgroupDriver() string {
  471. cgroupDriver := cgroupFsDriver
  472. if UsingSystemd(daemon.configStore) {
  473. cgroupDriver = cgroupSystemdDriver
  474. }
  475. return cgroupDriver
  476. }
  477. // getCD gets the raw value of the native.cgroupdriver option, if set.
  478. func getCD(config *config.Config) string {
  479. for _, option := range config.ExecOptions {
  480. key, val, err := parsers.ParseKeyValueOpt(option)
  481. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  482. continue
  483. }
  484. return val
  485. }
  486. return ""
  487. }
  488. // VerifyCgroupDriver validates native.cgroupdriver
  489. func VerifyCgroupDriver(config *config.Config) error {
  490. cd := getCD(config)
  491. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  492. return nil
  493. }
  494. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  495. }
  496. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  497. func UsingSystemd(config *config.Config) bool {
  498. return getCD(config) == cgroupSystemdDriver
  499. }
  500. // verifyPlatformContainerSettings performs platform-specific validation of the
  501. // hostconfig and config structures.
  502. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  503. var warnings []string
  504. sysInfo := sysinfo.New(true)
  505. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  506. if err != nil {
  507. return warnings, err
  508. }
  509. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  510. // no matter err is nil or not, w could have data in itself.
  511. warnings = append(warnings, w...)
  512. if err != nil {
  513. return warnings, err
  514. }
  515. if hostConfig.ShmSize < 0 {
  516. return warnings, fmt.Errorf("SHM size can not be less than 0")
  517. }
  518. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  519. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  520. }
  521. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  522. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  523. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  524. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  525. }
  526. // check for various conflicting options with user namespaces
  527. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  528. if hostConfig.Privileged {
  529. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  530. }
  531. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  532. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  533. }
  534. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  535. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  536. }
  537. }
  538. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  539. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  540. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  541. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  542. }
  543. }
  544. if hostConfig.Runtime == "" {
  545. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  546. }
  547. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  548. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  549. }
  550. parser := volume.NewParser(runtime.GOOS)
  551. for dest := range hostConfig.Tmpfs {
  552. if err := parser.ValidateTmpfsMountDestination(dest); err != nil {
  553. return warnings, err
  554. }
  555. }
  556. return warnings, nil
  557. }
  558. // reloadPlatform updates configuration with platform specific options
  559. // and updates the passed attributes
  560. func (daemon *Daemon) reloadPlatform(conf *config.Config, attributes map[string]string) error {
  561. if err := conf.ValidatePlatformConfig(); err != nil {
  562. return err
  563. }
  564. if conf.IsValueSet("runtimes") {
  565. daemon.configStore.Runtimes = conf.Runtimes
  566. // Always set the default one
  567. daemon.configStore.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  568. }
  569. if conf.DefaultRuntime != "" {
  570. daemon.configStore.DefaultRuntime = conf.DefaultRuntime
  571. }
  572. if conf.IsValueSet("default-shm-size") {
  573. daemon.configStore.ShmSize = conf.ShmSize
  574. }
  575. if conf.IpcMode != "" {
  576. daemon.configStore.IpcMode = conf.IpcMode
  577. }
  578. // Update attributes
  579. var runtimeList bytes.Buffer
  580. for name, rt := range daemon.configStore.Runtimes {
  581. if runtimeList.Len() > 0 {
  582. runtimeList.WriteRune(' ')
  583. }
  584. runtimeList.WriteString(fmt.Sprintf("%s:%s", name, rt))
  585. }
  586. attributes["runtimes"] = runtimeList.String()
  587. attributes["default-runtime"] = daemon.configStore.DefaultRuntime
  588. attributes["default-shm-size"] = fmt.Sprintf("%d", daemon.configStore.ShmSize)
  589. attributes["default-ipc-mode"] = daemon.configStore.IpcMode
  590. return nil
  591. }
  592. // verifyDaemonSettings performs validation of daemon config struct
  593. func verifyDaemonSettings(conf *config.Config) error {
  594. // Check for mutually incompatible config options
  595. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  596. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  597. }
  598. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  599. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  600. }
  601. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  602. conf.BridgeConfig.EnableIPMasq = false
  603. }
  604. if err := VerifyCgroupDriver(conf); err != nil {
  605. return err
  606. }
  607. if conf.CgroupParent != "" && UsingSystemd(conf) {
  608. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  609. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  610. }
  611. }
  612. if conf.DefaultRuntime == "" {
  613. conf.DefaultRuntime = config.StockRuntimeName
  614. }
  615. if conf.Runtimes == nil {
  616. conf.Runtimes = make(map[string]types.Runtime)
  617. }
  618. conf.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  619. return nil
  620. }
  621. // checkSystem validates platform-specific requirements
  622. func checkSystem() error {
  623. if os.Geteuid() != 0 {
  624. return fmt.Errorf("The Docker daemon needs to be run as root")
  625. }
  626. return checkKernel()
  627. }
  628. // configureMaxThreads sets the Go runtime max threads threshold
  629. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  630. func configureMaxThreads(config *config.Config) error {
  631. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  632. if err != nil {
  633. return err
  634. }
  635. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  636. if err != nil {
  637. return err
  638. }
  639. maxThreads := (mtint / 100) * 90
  640. debug.SetMaxThreads(maxThreads)
  641. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  642. return nil
  643. }
  644. func overlaySupportsSelinux() (bool, error) {
  645. f, err := os.Open("/proc/kallsyms")
  646. if err != nil {
  647. if os.IsNotExist(err) {
  648. return false, nil
  649. }
  650. return false, err
  651. }
  652. defer f.Close()
  653. var symAddr, symType, symName, text string
  654. s := bufio.NewScanner(f)
  655. for s.Scan() {
  656. if err := s.Err(); err != nil {
  657. return false, err
  658. }
  659. text = s.Text()
  660. if _, err := fmt.Sscanf(text, "%s %s %s", &symAddr, &symType, &symName); err != nil {
  661. return false, fmt.Errorf("Scanning '%s' failed: %s", text, err)
  662. }
  663. // Check for presence of symbol security_inode_copy_up.
  664. if symName == "security_inode_copy_up" {
  665. return true, nil
  666. }
  667. }
  668. return false, nil
  669. }
  670. // configureKernelSecuritySupport configures and validates security support for the kernel
  671. func configureKernelSecuritySupport(config *config.Config, driverNames []string) error {
  672. if config.EnableSelinuxSupport {
  673. if !selinuxEnabled() {
  674. logrus.Warn("Docker could not enable SELinux on the host system")
  675. return nil
  676. }
  677. overlayFound := false
  678. for _, d := range driverNames {
  679. if d == "overlay" || d == "overlay2" {
  680. overlayFound = true
  681. break
  682. }
  683. }
  684. if overlayFound {
  685. // If driver is overlay or overlay2, make sure kernel
  686. // supports selinux with overlay.
  687. supported, err := overlaySupportsSelinux()
  688. if err != nil {
  689. return err
  690. }
  691. if !supported {
  692. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverNames)
  693. }
  694. }
  695. } else {
  696. selinuxSetDisabled()
  697. }
  698. return nil
  699. }
  700. func (daemon *Daemon) initNetworkController(config *config.Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  701. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  702. if err != nil {
  703. return nil, err
  704. }
  705. controller, err := libnetwork.New(netOptions...)
  706. if err != nil {
  707. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  708. }
  709. if len(activeSandboxes) > 0 {
  710. logrus.Info("There are old running containers, the network config will not take affect")
  711. return controller, nil
  712. }
  713. // Initialize default network on "null"
  714. if n, _ := controller.NetworkByName("none"); n == nil {
  715. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  716. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  717. }
  718. }
  719. // Initialize default network on "host"
  720. if n, _ := controller.NetworkByName("host"); n == nil {
  721. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  722. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  723. }
  724. }
  725. // Clear stale bridge network
  726. if n, err := controller.NetworkByName("bridge"); err == nil {
  727. if err = n.Delete(); err != nil {
  728. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  729. }
  730. }
  731. if !config.DisableBridge {
  732. // Initialize default driver "bridge"
  733. if err := initBridgeDriver(controller, config); err != nil {
  734. return nil, err
  735. }
  736. } else {
  737. removeDefaultBridgeInterface()
  738. }
  739. return controller, nil
  740. }
  741. func driverOptions(config *config.Config) []nwconfig.Option {
  742. bridgeConfig := options.Generic{
  743. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  744. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  745. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  746. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath}
  747. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  748. dOptions := []nwconfig.Option{}
  749. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  750. return dOptions
  751. }
  752. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  753. bridgeName := bridge.DefaultBridgeName
  754. if config.BridgeConfig.Iface != "" {
  755. bridgeName = config.BridgeConfig.Iface
  756. }
  757. netOption := map[string]string{
  758. bridge.BridgeName: bridgeName,
  759. bridge.DefaultBridge: strconv.FormatBool(true),
  760. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  761. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  762. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  763. }
  764. // --ip processing
  765. if config.BridgeConfig.DefaultIP != nil {
  766. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  767. }
  768. var (
  769. ipamV4Conf *libnetwork.IpamConf
  770. ipamV6Conf *libnetwork.IpamConf
  771. )
  772. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  773. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  774. if err != nil {
  775. return errors.Wrap(err, "list bridge addresses failed")
  776. }
  777. nw := nwList[0]
  778. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  779. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  780. if err != nil {
  781. return errors.Wrap(err, "parse CIDR failed")
  782. }
  783. // Iterate through in case there are multiple addresses for the bridge
  784. for _, entry := range nwList {
  785. if fCIDR.Contains(entry.IP) {
  786. nw = entry
  787. break
  788. }
  789. }
  790. }
  791. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  792. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  793. if hip.IsGlobalUnicast() {
  794. ipamV4Conf.Gateway = nw.IP.String()
  795. }
  796. if config.BridgeConfig.IP != "" {
  797. ipamV4Conf.PreferredPool = config.BridgeConfig.IP
  798. ip, _, err := net.ParseCIDR(config.BridgeConfig.IP)
  799. if err != nil {
  800. return err
  801. }
  802. ipamV4Conf.Gateway = ip.String()
  803. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  804. logrus.Infof("Default bridge (%s) is assigned with an IP address %s. Daemon option --bip can be used to set a preferred IP address", bridgeName, ipamV4Conf.PreferredPool)
  805. }
  806. if config.BridgeConfig.FixedCIDR != "" {
  807. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  808. if err != nil {
  809. return err
  810. }
  811. ipamV4Conf.SubPool = fCIDR.String()
  812. }
  813. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  814. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  815. }
  816. var deferIPv6Alloc bool
  817. if config.BridgeConfig.FixedCIDRv6 != "" {
  818. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  819. if err != nil {
  820. return err
  821. }
  822. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  823. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  824. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  825. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  826. // on this network until after the driver has created the endpoint and returned the
  827. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  828. ones, _ := fCIDRv6.Mask.Size()
  829. deferIPv6Alloc = ones <= 80
  830. if ipamV6Conf == nil {
  831. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  832. }
  833. ipamV6Conf.PreferredPool = fCIDRv6.String()
  834. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  835. // address belongs to the same network, we need to inform libnetwork about it, so
  836. // that it can be reserved with IPAM and it will not be given away to somebody else
  837. for _, nw6 := range nw6List {
  838. if fCIDRv6.Contains(nw6.IP) {
  839. ipamV6Conf.Gateway = nw6.IP.String()
  840. break
  841. }
  842. }
  843. }
  844. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  845. if ipamV6Conf == nil {
  846. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  847. }
  848. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  849. }
  850. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  851. v6Conf := []*libnetwork.IpamConf{}
  852. if ipamV6Conf != nil {
  853. v6Conf = append(v6Conf, ipamV6Conf)
  854. }
  855. // Initialize default network on "bridge" with the same name
  856. _, err = controller.NewNetwork("bridge", "bridge", "",
  857. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  858. libnetwork.NetworkOptionDriverOpts(netOption),
  859. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  860. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  861. if err != nil {
  862. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  863. }
  864. return nil
  865. }
  866. // Remove default bridge interface if present (--bridge=none use case)
  867. func removeDefaultBridgeInterface() {
  868. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  869. if err := netlink.LinkDel(lnk); err != nil {
  870. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  871. }
  872. }
  873. }
  874. func (daemon *Daemon) getLayerInit() func(string) error {
  875. return daemon.setupInitLayer
  876. }
  877. // Parse the remapped root (user namespace) option, which can be one of:
  878. // username - valid username from /etc/passwd
  879. // username:groupname - valid username; valid groupname from /etc/group
  880. // uid - 32-bit unsigned int valid Linux UID value
  881. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  882. //
  883. // If no groupname is specified, and a username is specified, an attempt
  884. // will be made to lookup a gid for that username as a groupname
  885. //
  886. // If names are used, they are verified to exist in passwd/group
  887. func parseRemappedRoot(usergrp string) (string, string, error) {
  888. var (
  889. userID, groupID int
  890. username, groupname string
  891. )
  892. idparts := strings.Split(usergrp, ":")
  893. if len(idparts) > 2 {
  894. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  895. }
  896. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  897. // must be a uid; take it as valid
  898. userID = int(uid)
  899. luser, err := idtools.LookupUID(userID)
  900. if err != nil {
  901. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  902. }
  903. username = luser.Name
  904. if len(idparts) == 1 {
  905. // if the uid was numeric and no gid was specified, take the uid as the gid
  906. groupID = userID
  907. lgrp, err := idtools.LookupGID(groupID)
  908. if err != nil {
  909. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  910. }
  911. groupname = lgrp.Name
  912. }
  913. } else {
  914. lookupName := idparts[0]
  915. // special case: if the user specified "default", they want Docker to create or
  916. // use (after creation) the "dockremap" user/group for root remapping
  917. if lookupName == defaultIDSpecifier {
  918. lookupName = defaultRemappedID
  919. }
  920. luser, err := idtools.LookupUser(lookupName)
  921. if err != nil && idparts[0] != defaultIDSpecifier {
  922. // error if the name requested isn't the special "dockremap" ID
  923. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  924. } else if err != nil {
  925. // special case-- if the username == "default", then we have been asked
  926. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  927. // ranges will be used for the user and group mappings in user namespaced containers
  928. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  929. if err == nil {
  930. return defaultRemappedID, defaultRemappedID, nil
  931. }
  932. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  933. }
  934. username = luser.Name
  935. if len(idparts) == 1 {
  936. // we only have a string username, and no group specified; look up gid from username as group
  937. group, err := idtools.LookupGroup(lookupName)
  938. if err != nil {
  939. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  940. }
  941. groupname = group.Name
  942. }
  943. }
  944. if len(idparts) == 2 {
  945. // groupname or gid is separately specified and must be resolved
  946. // to an unsigned 32-bit gid
  947. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  948. // must be a gid, take it as valid
  949. groupID = int(gid)
  950. lgrp, err := idtools.LookupGID(groupID)
  951. if err != nil {
  952. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  953. }
  954. groupname = lgrp.Name
  955. } else {
  956. // not a number; attempt a lookup
  957. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  958. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  959. }
  960. groupname = idparts[1]
  961. }
  962. }
  963. return username, groupname, nil
  964. }
  965. func setupRemappedRoot(config *config.Config) (*idtools.IDMappings, error) {
  966. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  967. return nil, fmt.Errorf("User namespaces are only supported on Linux")
  968. }
  969. // if the daemon was started with remapped root option, parse
  970. // the config option to the int uid,gid values
  971. if config.RemappedRoot != "" {
  972. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  973. if err != nil {
  974. return nil, err
  975. }
  976. if username == "root" {
  977. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  978. // effectively
  979. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  980. return &idtools.IDMappings{}, nil
  981. }
  982. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  983. // update remapped root setting now that we have resolved them to actual names
  984. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  985. mappings, err := idtools.NewIDMappings(username, groupname)
  986. if err != nil {
  987. return nil, errors.Wrapf(err, "Can't create ID mappings: %v")
  988. }
  989. return mappings, nil
  990. }
  991. return &idtools.IDMappings{}, nil
  992. }
  993. func setupDaemonRoot(config *config.Config, rootDir string, rootIDs idtools.IDPair) error {
  994. config.Root = rootDir
  995. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  996. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  997. // (e.g. mounted layers of a container) can traverse this path.
  998. // The user namespace support will create subdirectories for the remapped root host uid:gid
  999. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  1000. // layer content subtrees.
  1001. if _, err := os.Stat(rootDir); err == nil {
  1002. // root current exists; verify the access bits are correct by setting them
  1003. if err = os.Chmod(rootDir, 0711); err != nil {
  1004. return err
  1005. }
  1006. } else if os.IsNotExist(err) {
  1007. // no root exists yet, create it 0711 with root:root ownership
  1008. if err := os.MkdirAll(rootDir, 0711); err != nil {
  1009. return err
  1010. }
  1011. }
  1012. // if user namespaces are enabled we will create a subtree underneath the specified root
  1013. // with any/all specified remapped root uid/gid options on the daemon creating
  1014. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  1015. // `chdir()` to work for containers namespaced to that uid/gid)
  1016. if config.RemappedRoot != "" {
  1017. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootIDs.UID, rootIDs.GID))
  1018. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  1019. // Create the root directory if it doesn't exist
  1020. if err := idtools.MkdirAllAndChown(config.Root, 0700, rootIDs); err != nil {
  1021. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  1022. }
  1023. // we also need to verify that any pre-existing directories in the path to
  1024. // the graphroot won't block access to remapped root--if any pre-existing directory
  1025. // has strict permissions that don't allow "x", container start will fail, so
  1026. // better to warn and fail now
  1027. dirPath := config.Root
  1028. for {
  1029. dirPath = filepath.Dir(dirPath)
  1030. if dirPath == "/" {
  1031. break
  1032. }
  1033. if !idtools.CanAccess(dirPath, rootIDs) {
  1034. return fmt.Errorf("a subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories", config.Root)
  1035. }
  1036. }
  1037. }
  1038. return nil
  1039. }
  1040. // registerLinks writes the links to a file.
  1041. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1042. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1043. return nil
  1044. }
  1045. for _, l := range hostConfig.Links {
  1046. name, alias, err := opts.ParseLink(l)
  1047. if err != nil {
  1048. return err
  1049. }
  1050. child, err := daemon.GetContainer(name)
  1051. if err != nil {
  1052. return errors.Wrapf(err, "could not get container for %s", name)
  1053. }
  1054. for child.HostConfig.NetworkMode.IsContainer() {
  1055. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  1056. child, err = daemon.GetContainer(parts[1])
  1057. if err != nil {
  1058. return errors.Wrapf(err, "Could not get container for %s", parts[1])
  1059. }
  1060. }
  1061. if child.HostConfig.NetworkMode.IsHost() {
  1062. return runconfig.ErrConflictHostNetworkAndLinks
  1063. }
  1064. if err := daemon.registerLink(container, child, alias); err != nil {
  1065. return err
  1066. }
  1067. }
  1068. // After we load all the links into the daemon
  1069. // set them to nil on the hostconfig
  1070. _, err := container.WriteHostConfig()
  1071. return err
  1072. }
  1073. // conditionalMountOnStart is a platform specific helper function during the
  1074. // container start to call mount.
  1075. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1076. return daemon.Mount(container)
  1077. }
  1078. // conditionalUnmountOnCleanup is a platform specific helper function called
  1079. // during the cleanup of a container to unmount.
  1080. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1081. return daemon.Unmount(container)
  1082. }
  1083. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1084. if !c.IsRunning() {
  1085. return nil, errNotRunning(c.ID)
  1086. }
  1087. stats, err := daemon.containerd.Stats(c.ID)
  1088. if err != nil {
  1089. if strings.Contains(err.Error(), "container not found") {
  1090. return nil, containerNotFound(c.ID)
  1091. }
  1092. return nil, err
  1093. }
  1094. s := &types.StatsJSON{}
  1095. cgs := stats.CgroupStats
  1096. if cgs != nil {
  1097. s.BlkioStats = types.BlkioStats{
  1098. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  1099. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  1100. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  1101. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  1102. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  1103. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  1104. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  1105. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  1106. }
  1107. cpu := cgs.CpuStats
  1108. s.CPUStats = types.CPUStats{
  1109. CPUUsage: types.CPUUsage{
  1110. TotalUsage: cpu.CpuUsage.TotalUsage,
  1111. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  1112. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  1113. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  1114. },
  1115. ThrottlingData: types.ThrottlingData{
  1116. Periods: cpu.ThrottlingData.Periods,
  1117. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  1118. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  1119. },
  1120. }
  1121. mem := cgs.MemoryStats.Usage
  1122. s.MemoryStats = types.MemoryStats{
  1123. Usage: mem.Usage,
  1124. MaxUsage: mem.MaxUsage,
  1125. Stats: cgs.MemoryStats.Stats,
  1126. Failcnt: mem.Failcnt,
  1127. Limit: mem.Limit,
  1128. }
  1129. // if the container does not set memory limit, use the machineMemory
  1130. if mem.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1131. s.MemoryStats.Limit = daemon.machineMemory
  1132. }
  1133. if cgs.PidsStats != nil {
  1134. s.PidsStats = types.PidsStats{
  1135. Current: cgs.PidsStats.Current,
  1136. }
  1137. }
  1138. }
  1139. s.Read, err = ptypes.Timestamp(stats.Timestamp)
  1140. if err != nil {
  1141. return nil, err
  1142. }
  1143. return s, nil
  1144. }
  1145. // setDefaultIsolation determines the default isolation mode for the
  1146. // daemon to run in. This is only applicable on Windows
  1147. func (daemon *Daemon) setDefaultIsolation() error {
  1148. return nil
  1149. }
  1150. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1151. var layers []string
  1152. for _, l := range rootfs.DiffIDs {
  1153. layers = append(layers, l.String())
  1154. }
  1155. return types.RootFS{
  1156. Type: rootfs.Type,
  1157. Layers: layers,
  1158. }
  1159. }
  1160. // setupDaemonProcess sets various settings for the daemon's process
  1161. func setupDaemonProcess(config *config.Config) error {
  1162. // setup the daemons oom_score_adj
  1163. return setupOOMScoreAdj(config.OOMScoreAdjust)
  1164. }
  1165. func setupOOMScoreAdj(score int) error {
  1166. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1167. if err != nil {
  1168. return err
  1169. }
  1170. defer f.Close()
  1171. stringScore := strconv.Itoa(score)
  1172. _, err = f.WriteString(stringScore)
  1173. if os.IsPermission(err) {
  1174. // Setting oom_score_adj does not work in an
  1175. // unprivileged container. Ignore the error, but log
  1176. // it if we appear not to be in that situation.
  1177. if !rsystem.RunningInUserNS() {
  1178. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1179. }
  1180. return nil
  1181. }
  1182. return err
  1183. }
  1184. func (daemon *Daemon) initCgroupsPath(path string) error {
  1185. if path == "/" || path == "." {
  1186. return nil
  1187. }
  1188. if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
  1189. return nil
  1190. }
  1191. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1192. // for the period and runtime as this limits what the children can be set to.
  1193. daemon.initCgroupsPath(filepath.Dir(path))
  1194. mnt, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
  1195. if err != nil {
  1196. return err
  1197. }
  1198. // When docker is run inside docker, the root is based of the host cgroup.
  1199. // Should this be handled in runc/libcontainer/cgroups ?
  1200. if strings.HasPrefix(root, "/docker/") {
  1201. root = "/"
  1202. }
  1203. path = filepath.Join(mnt, root, path)
  1204. sysinfo := sysinfo.New(true)
  1205. if err := maybeCreateCPURealTimeFile(sysinfo.CPURealtimePeriod, daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1206. return err
  1207. }
  1208. if err := maybeCreateCPURealTimeFile(sysinfo.CPURealtimeRuntime, daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path); err != nil {
  1209. return err
  1210. }
  1211. return nil
  1212. }
  1213. func maybeCreateCPURealTimeFile(sysinfoPresent bool, configValue int64, file string, path string) error {
  1214. if sysinfoPresent && configValue != 0 {
  1215. if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
  1216. return err
  1217. }
  1218. if err := ioutil.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700); err != nil {
  1219. return err
  1220. }
  1221. }
  1222. return nil
  1223. }
  1224. func (daemon *Daemon) setupSeccompProfile() error {
  1225. if daemon.configStore.SeccompProfile != "" {
  1226. daemon.seccompProfilePath = daemon.configStore.SeccompProfile
  1227. b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
  1228. if err != nil {
  1229. return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
  1230. }
  1231. daemon.seccompProfile = b
  1232. }
  1233. return nil
  1234. }