daemon_unix.go 41 KB

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