daemon_unix.go 55 KB

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