daemon_unix.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/container"
  18. "github.com/docker/docker/image"
  19. "github.com/docker/docker/layer"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/parsers"
  22. "github.com/docker/docker/pkg/parsers/kernel"
  23. "github.com/docker/docker/pkg/sysinfo"
  24. "github.com/docker/docker/reference"
  25. "github.com/docker/docker/runconfig"
  26. runconfigopts "github.com/docker/docker/runconfig/opts"
  27. "github.com/docker/engine-api/types"
  28. "github.com/docker/engine-api/types/blkiodev"
  29. pblkiodev "github.com/docker/engine-api/types/blkiodev"
  30. containertypes "github.com/docker/engine-api/types/container"
  31. "github.com/docker/libnetwork"
  32. nwconfig "github.com/docker/libnetwork/config"
  33. "github.com/docker/libnetwork/drivers/bridge"
  34. "github.com/docker/libnetwork/netlabel"
  35. "github.com/docker/libnetwork/netutils"
  36. "github.com/docker/libnetwork/options"
  37. lntypes "github.com/docker/libnetwork/types"
  38. "github.com/opencontainers/runc/libcontainer/label"
  39. "github.com/opencontainers/runc/libcontainer/user"
  40. "github.com/opencontainers/specs/specs-go"
  41. )
  42. const (
  43. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  44. linuxMinCPUShares = 2
  45. linuxMaxCPUShares = 262144
  46. platformSupported = true
  47. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  48. linuxMinMemory = 4194304
  49. // constants for remapped root settings
  50. defaultIDSpecifier string = "default"
  51. defaultRemappedID string = "dockremap"
  52. // constant for cgroup drivers
  53. cgroupFsDriver = "cgroupfs"
  54. cgroupSystemdDriver = "systemd"
  55. )
  56. func getMemoryResources(config containertypes.Resources) *specs.Memory {
  57. memory := specs.Memory{}
  58. if config.Memory > 0 {
  59. limit := uint64(config.Memory)
  60. memory.Limit = &limit
  61. }
  62. if config.MemoryReservation > 0 {
  63. reservation := uint64(config.MemoryReservation)
  64. memory.Reservation = &reservation
  65. }
  66. if config.MemorySwap != 0 {
  67. swap := uint64(config.MemorySwap)
  68. memory.Swap = &swap
  69. }
  70. if config.MemorySwappiness != nil {
  71. swappiness := uint64(*config.MemorySwappiness)
  72. memory.Swappiness = &swappiness
  73. }
  74. if config.KernelMemory != 0 {
  75. kernelMemory := uint64(config.KernelMemory)
  76. memory.Kernel = &kernelMemory
  77. }
  78. return &memory
  79. }
  80. func getCPUResources(config containertypes.Resources) *specs.CPU {
  81. cpu := specs.CPU{}
  82. if config.CPUShares != 0 {
  83. shares := uint64(config.CPUShares)
  84. cpu.Shares = &shares
  85. }
  86. if config.CpusetCpus != "" {
  87. cpuset := config.CpusetCpus
  88. cpu.Cpus = &cpuset
  89. }
  90. if config.CpusetMems != "" {
  91. cpuset := config.CpusetMems
  92. cpu.Mems = &cpuset
  93. }
  94. if config.CPUPeriod != 0 {
  95. period := uint64(config.CPUPeriod)
  96. cpu.Period = &period
  97. }
  98. if config.CPUQuota != 0 {
  99. quota := uint64(config.CPUQuota)
  100. cpu.Quota = &quota
  101. }
  102. return &cpu
  103. }
  104. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.WeightDevice, error) {
  105. var stat syscall.Stat_t
  106. var blkioWeightDevices []specs.WeightDevice
  107. for _, weightDevice := range config.BlkioWeightDevice {
  108. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  109. return nil, err
  110. }
  111. weight := weightDevice.Weight
  112. d := specs.WeightDevice{Weight: &weight}
  113. d.Major = int64(stat.Rdev / 256)
  114. d.Minor = int64(stat.Rdev % 256)
  115. blkioWeightDevices = append(blkioWeightDevices, d)
  116. }
  117. return blkioWeightDevices, nil
  118. }
  119. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  120. var (
  121. labelOpts []string
  122. err error
  123. )
  124. for _, opt := range config.SecurityOpt {
  125. if opt == "no-new-privileges" {
  126. container.NoNewPrivileges = true
  127. } else {
  128. var con []string
  129. if strings.Contains(opt, "=") {
  130. con = strings.SplitN(opt, "=", 2)
  131. } else if strings.Contains(opt, ":") {
  132. con = strings.SplitN(opt, ":", 2)
  133. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 1.13, use `=` instead.")
  134. }
  135. if len(con) != 2 {
  136. return fmt.Errorf("Invalid --security-opt 1: %q", opt)
  137. }
  138. switch con[0] {
  139. case "label":
  140. labelOpts = append(labelOpts, con[1])
  141. case "apparmor":
  142. container.AppArmorProfile = con[1]
  143. case "seccomp":
  144. container.SeccompProfile = con[1]
  145. default:
  146. return fmt.Errorf("Invalid --security-opt 2: %q", opt)
  147. }
  148. }
  149. }
  150. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  151. return err
  152. }
  153. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.ThrottleDevice, error) {
  154. var throttleDevices []specs.ThrottleDevice
  155. var stat syscall.Stat_t
  156. for _, d := range devs {
  157. if err := syscall.Stat(d.Path, &stat); err != nil {
  158. return nil, err
  159. }
  160. rate := d.Rate
  161. d := specs.ThrottleDevice{Rate: &rate}
  162. d.Major = int64(stat.Rdev / 256)
  163. d.Minor = int64(stat.Rdev % 256)
  164. throttleDevices = append(throttleDevices, d)
  165. }
  166. return throttleDevices, nil
  167. }
  168. func checkKernelVersion(k, major, minor int) bool {
  169. if v, err := kernel.GetKernelVersion(); err != nil {
  170. logrus.Warnf("error getting kernel version: %s", err)
  171. } else {
  172. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  173. return false
  174. }
  175. }
  176. return true
  177. }
  178. func checkKernel() error {
  179. // Check for unsupported kernel versions
  180. // FIXME: it would be cleaner to not test for specific versions, but rather
  181. // test for specific functionalities.
  182. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  183. // without actually causing a kernel panic, so we need this workaround until
  184. // the circumstances of pre-3.10 crashes are clearer.
  185. // For details see https://github.com/docker/docker/issues/407
  186. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  187. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  188. if !checkKernelVersion(3, 10, 0) {
  189. v, _ := kernel.GetKernelVersion()
  190. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  191. 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())
  192. }
  193. }
  194. return nil
  195. }
  196. // adaptContainerSettings is called during container creation to modify any
  197. // settings necessary in the HostConfig structure.
  198. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  199. if adjustCPUShares && hostConfig.CPUShares > 0 {
  200. // Handle unsupported CPUShares
  201. if hostConfig.CPUShares < linuxMinCPUShares {
  202. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  203. hostConfig.CPUShares = linuxMinCPUShares
  204. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  205. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  206. hostConfig.CPUShares = linuxMaxCPUShares
  207. }
  208. }
  209. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  210. // By default, MemorySwap is set to twice the size of Memory.
  211. hostConfig.MemorySwap = hostConfig.Memory * 2
  212. }
  213. if hostConfig.ShmSize == 0 {
  214. hostConfig.ShmSize = container.DefaultSHMSize
  215. }
  216. var err error
  217. if hostConfig.SecurityOpt == nil {
  218. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged)
  219. if err != nil {
  220. return err
  221. }
  222. }
  223. if hostConfig.MemorySwappiness == nil {
  224. defaultSwappiness := int64(-1)
  225. hostConfig.MemorySwappiness = &defaultSwappiness
  226. }
  227. if hostConfig.OomKillDisable == nil {
  228. defaultOomKillDisable := false
  229. hostConfig.OomKillDisable = &defaultOomKillDisable
  230. }
  231. return nil
  232. }
  233. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  234. warnings := []string{}
  235. // memory subsystem checks and adjustments
  236. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  237. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  238. }
  239. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  240. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  241. logrus.Warn("Your kernel does not support memory limit capabilities. Limitation discarded.")
  242. resources.Memory = 0
  243. resources.MemorySwap = -1
  244. }
  245. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  246. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  247. logrus.Warn("Your kernel does not support swap limit capabilities, memory limited without swap.")
  248. resources.MemorySwap = -1
  249. }
  250. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  251. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  252. }
  253. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  254. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  255. }
  256. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  257. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  258. logrus.Warn("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  259. resources.MemorySwappiness = nil
  260. }
  261. if resources.MemorySwappiness != nil {
  262. swappiness := *resources.MemorySwappiness
  263. if swappiness < -1 || swappiness > 100 {
  264. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  265. }
  266. }
  267. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  268. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  269. logrus.Warn("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  270. resources.MemoryReservation = 0
  271. }
  272. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  273. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  274. }
  275. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  276. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage")
  277. }
  278. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  279. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  280. logrus.Warn("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  281. resources.KernelMemory = 0
  282. }
  283. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  284. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  285. }
  286. if resources.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  287. 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.")
  288. 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.")
  289. }
  290. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  291. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  292. // warning the caller if they already wanted the feature to be off
  293. if *resources.OomKillDisable {
  294. warnings = append(warnings, "Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  295. logrus.Warn("Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  296. }
  297. resources.OomKillDisable = nil
  298. }
  299. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  300. warnings = append(warnings, "Your kernel does not support pids limit capabilities, pids limit discarded.")
  301. logrus.Warn("Your kernel does not support pids limit capabilities, pids limit discarded.")
  302. resources.PidsLimit = 0
  303. }
  304. // cpu subsystem checks and adjustments
  305. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  306. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  307. logrus.Warn("Your kernel does not support CPU shares. Shares discarded.")
  308. resources.CPUShares = 0
  309. }
  310. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  311. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  312. logrus.Warn("Your kernel does not support CPU cfs period. Period discarded.")
  313. resources.CPUPeriod = 0
  314. }
  315. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  316. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  317. }
  318. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  319. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  320. logrus.Warn("Your kernel does not support CPU cfs quota. Quota discarded.")
  321. resources.CPUQuota = 0
  322. }
  323. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  324. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  325. }
  326. if resources.CPUPercent > 0 {
  327. warnings = append(warnings, "%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  328. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  329. resources.CPUPercent = 0
  330. }
  331. // cpuset subsystem checks and adjustments
  332. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  333. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  334. logrus.Warn("Your kernel does not support cpuset. Cpuset discarded.")
  335. resources.CpusetCpus = ""
  336. resources.CpusetMems = ""
  337. }
  338. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  339. if err != nil {
  340. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  341. }
  342. if !cpusAvailable {
  343. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  344. }
  345. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  346. if err != nil {
  347. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  348. }
  349. if !memsAvailable {
  350. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  351. }
  352. // blkio subsystem checks and adjustments
  353. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  354. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  355. logrus.Warn("Your kernel does not support Block I/O weight. Weight discarded.")
  356. resources.BlkioWeight = 0
  357. }
  358. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  359. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  360. }
  361. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  362. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  363. }
  364. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  365. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  366. logrus.Warn("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  367. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  368. }
  369. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  370. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  371. logrus.Warn("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  372. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  373. }
  374. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  375. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  376. logrus.Warn("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  377. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  378. }
  379. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  380. warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
  381. logrus.Warn("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
  382. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  383. }
  384. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  385. warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
  386. logrus.Warn("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
  387. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  388. }
  389. return warnings, nil
  390. }
  391. func (daemon *Daemon) getCgroupDriver() string {
  392. cgroupDriver := cgroupFsDriver
  393. if UsingSystemd(daemon.configStore) {
  394. cgroupDriver = cgroupSystemdDriver
  395. }
  396. return cgroupDriver
  397. }
  398. // getCD gets the raw value of the native.cgroupdriver option, if set.
  399. func getCD(config *Config) string {
  400. for _, option := range config.ExecOptions {
  401. key, val, err := parsers.ParseKeyValueOpt(option)
  402. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  403. continue
  404. }
  405. return val
  406. }
  407. return ""
  408. }
  409. // VerifyCgroupDriver validates native.cgroupdriver
  410. func VerifyCgroupDriver(config *Config) error {
  411. cd := getCD(config)
  412. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  413. return nil
  414. }
  415. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  416. }
  417. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  418. func UsingSystemd(config *Config) bool {
  419. return getCD(config) == cgroupSystemdDriver
  420. }
  421. // verifyPlatformContainerSettings performs platform-specific validation of the
  422. // hostconfig and config structures.
  423. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  424. warnings := []string{}
  425. sysInfo := sysinfo.New(true)
  426. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  427. if err != nil {
  428. return warnings, err
  429. }
  430. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  431. if err != nil {
  432. return warnings, err
  433. }
  434. warnings = append(warnings, w...)
  435. if hostConfig.ShmSize < 0 {
  436. return warnings, fmt.Errorf("SHM size must be greater than 0")
  437. }
  438. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  439. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  440. }
  441. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  442. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  443. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  444. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  445. }
  446. // check for various conflicting options with user namespaces
  447. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  448. if hostConfig.Privileged {
  449. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  450. }
  451. if hostConfig.NetworkMode.IsHost() {
  452. return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
  453. }
  454. if hostConfig.PidMode.IsHost() {
  455. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  456. }
  457. if hostConfig.ReadonlyRootfs {
  458. return warnings, fmt.Errorf("Cannot use the --read-only option when user namespaces are enabled")
  459. }
  460. }
  461. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  462. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  463. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  464. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  465. }
  466. }
  467. if hostConfig.Runtime == "" {
  468. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  469. }
  470. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  471. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  472. }
  473. return warnings, nil
  474. }
  475. // platformReload update configuration with platform specific options
  476. func (daemon *Daemon) platformReload(config *Config, attributes *map[string]string) {
  477. if config.IsValueSet("runtimes") {
  478. daemon.configStore.Runtimes = config.Runtimes
  479. // Always set the default one
  480. daemon.configStore.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary}
  481. }
  482. if config.DefaultRuntime != "" {
  483. daemon.configStore.DefaultRuntime = config.DefaultRuntime
  484. }
  485. // Update attributes
  486. var runtimeList bytes.Buffer
  487. for name, rt := range daemon.configStore.Runtimes {
  488. if runtimeList.Len() > 0 {
  489. runtimeList.WriteRune(' ')
  490. }
  491. runtimeList.WriteString(fmt.Sprintf("%s:%s", name, rt))
  492. }
  493. (*attributes)["runtimes"] = runtimeList.String()
  494. (*attributes)["default-runtime"] = daemon.configStore.DefaultRuntime
  495. }
  496. // verifyDaemonSettings performs validation of daemon config struct
  497. func verifyDaemonSettings(config *Config) error {
  498. // Check for mutually incompatible config options
  499. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  500. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  501. }
  502. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  503. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  504. }
  505. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  506. config.bridgeConfig.EnableIPMasq = false
  507. }
  508. if err := VerifyCgroupDriver(config); err != nil {
  509. return err
  510. }
  511. if config.CgroupParent != "" && UsingSystemd(config) {
  512. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  513. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  514. }
  515. }
  516. if config.DefaultRuntime == "" {
  517. config.DefaultRuntime = stockRuntimeName
  518. }
  519. if config.Runtimes == nil {
  520. config.Runtimes = make(map[string]types.Runtime)
  521. }
  522. stockRuntimeOpts := []string{}
  523. if UsingSystemd(config) {
  524. stockRuntimeOpts = append(stockRuntimeOpts, "--systemd-cgroup=true")
  525. }
  526. config.Runtimes[stockRuntimeName] = types.Runtime{Path: DefaultRuntimeBinary, Args: stockRuntimeOpts}
  527. return nil
  528. }
  529. // checkSystem validates platform-specific requirements
  530. func checkSystem() error {
  531. if os.Geteuid() != 0 {
  532. return fmt.Errorf("The Docker daemon needs to be run as root")
  533. }
  534. return checkKernel()
  535. }
  536. // configureMaxThreads sets the Go runtime max threads threshold
  537. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  538. func configureMaxThreads(config *Config) error {
  539. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  540. if err != nil {
  541. return err
  542. }
  543. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  544. if err != nil {
  545. return err
  546. }
  547. maxThreads := (mtint / 100) * 90
  548. debug.SetMaxThreads(maxThreads)
  549. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  550. return nil
  551. }
  552. // configureKernelSecuritySupport configures and validates security support for the kernel
  553. func configureKernelSecuritySupport(config *Config, driverName string) error {
  554. if config.EnableSelinuxSupport {
  555. if selinuxEnabled() {
  556. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  557. if driverName == "overlay" {
  558. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  559. }
  560. logrus.Debug("SELinux enabled successfully")
  561. } else {
  562. logrus.Warn("Docker could not enable SELinux on the host system")
  563. }
  564. } else {
  565. selinuxSetDisabled()
  566. }
  567. return nil
  568. }
  569. func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  570. netOptions, err := daemon.networkOptions(config, activeSandboxes)
  571. if err != nil {
  572. return nil, err
  573. }
  574. controller, err := libnetwork.New(netOptions...)
  575. if err != nil {
  576. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  577. }
  578. if len(activeSandboxes) > 0 {
  579. logrus.Infof("There are old running containers, the network config will not take affect")
  580. return controller, nil
  581. }
  582. // Initialize default network on "null"
  583. if n, _ := controller.NetworkByName("none"); n == nil {
  584. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  585. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  586. }
  587. }
  588. // Initialize default network on "host"
  589. if n, _ := controller.NetworkByName("host"); n == nil {
  590. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  591. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  592. }
  593. }
  594. if !config.DisableBridge {
  595. // Initialize default driver "bridge"
  596. if err := initBridgeDriver(controller, config); err != nil {
  597. return nil, err
  598. }
  599. }
  600. return controller, nil
  601. }
  602. func driverOptions(config *Config) []nwconfig.Option {
  603. bridgeConfig := options.Generic{
  604. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  605. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  606. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy}
  607. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  608. dOptions := []nwconfig.Option{}
  609. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  610. return dOptions
  611. }
  612. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  613. if n, err := controller.NetworkByName("bridge"); err == nil {
  614. if err = n.Delete(); err != nil {
  615. return fmt.Errorf("could not delete the default bridge network: %v", err)
  616. }
  617. }
  618. bridgeName := bridge.DefaultBridgeName
  619. if config.bridgeConfig.Iface != "" {
  620. bridgeName = config.bridgeConfig.Iface
  621. }
  622. netOption := map[string]string{
  623. bridge.BridgeName: bridgeName,
  624. bridge.DefaultBridge: strconv.FormatBool(true),
  625. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  626. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  627. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  628. }
  629. // --ip processing
  630. if config.bridgeConfig.DefaultIP != nil {
  631. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  632. }
  633. var (
  634. ipamV4Conf *libnetwork.IpamConf
  635. ipamV6Conf *libnetwork.IpamConf
  636. )
  637. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  638. nw, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  639. if err == nil {
  640. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  641. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  642. if hip.IsGlobalUnicast() {
  643. ipamV4Conf.Gateway = nw.IP.String()
  644. }
  645. }
  646. if config.bridgeConfig.IP != "" {
  647. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  648. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  649. if err != nil {
  650. return err
  651. }
  652. ipamV4Conf.Gateway = ip.String()
  653. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  654. 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)
  655. }
  656. if config.bridgeConfig.FixedCIDR != "" {
  657. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  658. if err != nil {
  659. return err
  660. }
  661. ipamV4Conf.SubPool = fCIDR.String()
  662. }
  663. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  664. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  665. }
  666. var deferIPv6Alloc bool
  667. if config.bridgeConfig.FixedCIDRv6 != "" {
  668. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  669. if err != nil {
  670. return err
  671. }
  672. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  673. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  674. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  675. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  676. // on this network until after the driver has created the endpoint and returned the
  677. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  678. ones, _ := fCIDRv6.Mask.Size()
  679. deferIPv6Alloc = ones <= 80
  680. if ipamV6Conf == nil {
  681. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  682. }
  683. ipamV6Conf.PreferredPool = fCIDRv6.String()
  684. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  685. // address belongs to the same network, we need to inform libnetwork about it, so
  686. // that it can be reserved with IPAM and it will not be given away to somebody else
  687. for _, nw6 := range nw6List {
  688. if fCIDRv6.Contains(nw6.IP) {
  689. ipamV6Conf.Gateway = nw6.IP.String()
  690. break
  691. }
  692. }
  693. }
  694. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  695. if ipamV6Conf == nil {
  696. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  697. }
  698. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  699. }
  700. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  701. v6Conf := []*libnetwork.IpamConf{}
  702. if ipamV6Conf != nil {
  703. v6Conf = append(v6Conf, ipamV6Conf)
  704. }
  705. // Initialize default network on "bridge" with the same name
  706. _, err = controller.NewNetwork("bridge", "bridge", "",
  707. libnetwork.NetworkOptionEnableIPv6(config.bridgeConfig.EnableIPv6),
  708. libnetwork.NetworkOptionDriverOpts(netOption),
  709. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  710. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  711. if err != nil {
  712. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  713. }
  714. return nil
  715. }
  716. // setupInitLayer populates a directory with mountpoints suitable
  717. // for bind-mounting things into the container.
  718. //
  719. // This extra layer is used by all containers as the top-most ro layer. It protects
  720. // the container from unwanted side-effects on the rw layer.
  721. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  722. for pth, typ := range map[string]string{
  723. "/dev/pts": "dir",
  724. "/dev/shm": "dir",
  725. "/proc": "dir",
  726. "/sys": "dir",
  727. "/.dockerenv": "file",
  728. "/etc/resolv.conf": "file",
  729. "/etc/hosts": "file",
  730. "/etc/hostname": "file",
  731. "/dev/console": "file",
  732. "/etc/mtab": "/proc/mounts",
  733. } {
  734. parts := strings.Split(pth, "/")
  735. prev := "/"
  736. for _, p := range parts[1:] {
  737. prev = filepath.Join(prev, p)
  738. syscall.Unlink(filepath.Join(initLayer, prev))
  739. }
  740. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  741. if os.IsNotExist(err) {
  742. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  743. return err
  744. }
  745. switch typ {
  746. case "dir":
  747. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  748. return err
  749. }
  750. case "file":
  751. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  752. if err != nil {
  753. return err
  754. }
  755. f.Chown(rootUID, rootGID)
  756. f.Close()
  757. default:
  758. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  759. return err
  760. }
  761. }
  762. } else {
  763. return err
  764. }
  765. }
  766. }
  767. // Layer is ready to use, if it wasn't before.
  768. return nil
  769. }
  770. // Parse the remapped root (user namespace) option, which can be one of:
  771. // username - valid username from /etc/passwd
  772. // username:groupname - valid username; valid groupname from /etc/group
  773. // uid - 32-bit unsigned int valid Linux UID value
  774. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  775. //
  776. // If no groupname is specified, and a username is specified, an attempt
  777. // will be made to lookup a gid for that username as a groupname
  778. //
  779. // If names are used, they are verified to exist in passwd/group
  780. func parseRemappedRoot(usergrp string) (string, string, error) {
  781. var (
  782. userID, groupID int
  783. username, groupname string
  784. )
  785. idparts := strings.Split(usergrp, ":")
  786. if len(idparts) > 2 {
  787. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  788. }
  789. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  790. // must be a uid; take it as valid
  791. userID = int(uid)
  792. luser, err := user.LookupUid(userID)
  793. if err != nil {
  794. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  795. }
  796. username = luser.Name
  797. if len(idparts) == 1 {
  798. // if the uid was numeric and no gid was specified, take the uid as the gid
  799. groupID = userID
  800. lgrp, err := user.LookupGid(groupID)
  801. if err != nil {
  802. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  803. }
  804. groupname = lgrp.Name
  805. }
  806. } else {
  807. lookupName := idparts[0]
  808. // special case: if the user specified "default", they want Docker to create or
  809. // use (after creation) the "dockremap" user/group for root remapping
  810. if lookupName == defaultIDSpecifier {
  811. lookupName = defaultRemappedID
  812. }
  813. luser, err := user.LookupUser(lookupName)
  814. if err != nil && idparts[0] != defaultIDSpecifier {
  815. // error if the name requested isn't the special "dockremap" ID
  816. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  817. } else if err != nil {
  818. // special case-- if the username == "default", then we have been asked
  819. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  820. // ranges will be used for the user and group mappings in user namespaced containers
  821. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  822. if err == nil {
  823. return defaultRemappedID, defaultRemappedID, nil
  824. }
  825. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  826. }
  827. username = luser.Name
  828. if len(idparts) == 1 {
  829. // we only have a string username, and no group specified; look up gid from username as group
  830. group, err := user.LookupGroup(lookupName)
  831. if err != nil {
  832. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  833. }
  834. groupID = group.Gid
  835. groupname = group.Name
  836. }
  837. }
  838. if len(idparts) == 2 {
  839. // groupname or gid is separately specified and must be resolved
  840. // to an unsigned 32-bit gid
  841. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  842. // must be a gid, take it as valid
  843. groupID = int(gid)
  844. lgrp, err := user.LookupGid(groupID)
  845. if err != nil {
  846. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  847. }
  848. groupname = lgrp.Name
  849. } else {
  850. // not a number; attempt a lookup
  851. if _, err := user.LookupGroup(idparts[1]); err != nil {
  852. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  853. }
  854. groupname = idparts[1]
  855. }
  856. }
  857. return username, groupname, nil
  858. }
  859. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  860. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  861. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  862. }
  863. // if the daemon was started with remapped root option, parse
  864. // the config option to the int uid,gid values
  865. var (
  866. uidMaps, gidMaps []idtools.IDMap
  867. )
  868. if config.RemappedRoot != "" {
  869. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  870. if err != nil {
  871. return nil, nil, err
  872. }
  873. if username == "root" {
  874. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  875. // effectively
  876. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  877. return uidMaps, gidMaps, nil
  878. }
  879. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  880. // update remapped root setting now that we have resolved them to actual names
  881. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  882. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  883. if err != nil {
  884. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  885. }
  886. }
  887. return uidMaps, gidMaps, nil
  888. }
  889. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  890. config.Root = rootDir
  891. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  892. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  893. // (e.g. mounted layers of a container) can traverse this path.
  894. // The user namespace support will create subdirectories for the remapped root host uid:gid
  895. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  896. // layer content subtrees.
  897. if _, err := os.Stat(rootDir); err == nil {
  898. // root current exists; verify the access bits are correct by setting them
  899. if err = os.Chmod(rootDir, 0711); err != nil {
  900. return err
  901. }
  902. } else if os.IsNotExist(err) {
  903. // no root exists yet, create it 0711 with root:root ownership
  904. if err := os.MkdirAll(rootDir, 0711); err != nil {
  905. return err
  906. }
  907. }
  908. // if user namespaces are enabled we will create a subtree underneath the specified root
  909. // with any/all specified remapped root uid/gid options on the daemon creating
  910. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  911. // `chdir()` to work for containers namespaced to that uid/gid)
  912. if config.RemappedRoot != "" {
  913. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  914. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  915. // Create the root directory if it doesn't exist
  916. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  917. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  918. }
  919. }
  920. return nil
  921. }
  922. // registerLinks writes the links to a file.
  923. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  924. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  925. return nil
  926. }
  927. for _, l := range hostConfig.Links {
  928. name, alias, err := runconfigopts.ParseLink(l)
  929. if err != nil {
  930. return err
  931. }
  932. child, err := daemon.GetContainer(name)
  933. if err != nil {
  934. return fmt.Errorf("Could not get container for %s", name)
  935. }
  936. for child.HostConfig.NetworkMode.IsContainer() {
  937. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  938. child, err = daemon.GetContainer(parts[1])
  939. if err != nil {
  940. return fmt.Errorf("Could not get container for %s", parts[1])
  941. }
  942. }
  943. if child.HostConfig.NetworkMode.IsHost() {
  944. return runconfig.ErrConflictHostNetworkAndLinks
  945. }
  946. if err := daemon.registerLink(container, child, alias); err != nil {
  947. return err
  948. }
  949. }
  950. // After we load all the links into the daemon
  951. // set them to nil on the hostconfig
  952. return container.WriteHostConfig()
  953. }
  954. // conditionalMountOnStart is a platform specific helper function during the
  955. // container start to call mount.
  956. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  957. return daemon.Mount(container)
  958. }
  959. // conditionalUnmountOnCleanup is a platform specific helper function called
  960. // during the cleanup of a container to unmount.
  961. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  962. return daemon.Unmount(container)
  963. }
  964. func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
  965. // Unix has no custom images to register
  966. return nil
  967. }
  968. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  969. if !c.IsRunning() {
  970. return nil, errNotRunning{c.ID}
  971. }
  972. stats, err := daemon.containerd.Stats(c.ID)
  973. if err != nil {
  974. return nil, err
  975. }
  976. s := &types.StatsJSON{}
  977. cgs := stats.CgroupStats
  978. if cgs != nil {
  979. s.BlkioStats = types.BlkioStats{
  980. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  981. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  982. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  983. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  984. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  985. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  986. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  987. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  988. }
  989. cpu := cgs.CpuStats
  990. s.CPUStats = types.CPUStats{
  991. CPUUsage: types.CPUUsage{
  992. TotalUsage: cpu.CpuUsage.TotalUsage,
  993. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  994. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  995. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  996. },
  997. ThrottlingData: types.ThrottlingData{
  998. Periods: cpu.ThrottlingData.Periods,
  999. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  1000. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  1001. },
  1002. }
  1003. mem := cgs.MemoryStats.Usage
  1004. s.MemoryStats = types.MemoryStats{
  1005. Usage: mem.Usage,
  1006. MaxUsage: mem.MaxUsage,
  1007. Stats: cgs.MemoryStats.Stats,
  1008. Failcnt: mem.Failcnt,
  1009. Limit: mem.Limit,
  1010. }
  1011. // if the container does not set memory limit, use the machineMemory
  1012. if mem.Limit > daemon.statsCollector.machineMemory && daemon.statsCollector.machineMemory > 0 {
  1013. s.MemoryStats.Limit = daemon.statsCollector.machineMemory
  1014. }
  1015. if cgs.PidsStats != nil {
  1016. s.PidsStats = types.PidsStats{
  1017. Current: cgs.PidsStats.Current,
  1018. }
  1019. }
  1020. }
  1021. s.Read = time.Unix(int64(stats.Timestamp), 0)
  1022. return s, nil
  1023. }
  1024. // setDefaultIsolation determines the default isolation mode for the
  1025. // daemon to run in. This is only applicable on Windows
  1026. func (daemon *Daemon) setDefaultIsolation() error {
  1027. return nil
  1028. }
  1029. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1030. var layers []string
  1031. for _, l := range rootfs.DiffIDs {
  1032. layers = append(layers, l.String())
  1033. }
  1034. return types.RootFS{
  1035. Type: rootfs.Type,
  1036. Layers: layers,
  1037. }
  1038. }