daemon_unix.go 39 KB

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