driver_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // +build !windows
  2. package execdriver
  3. import (
  4. "encoding/json"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/docker/docker/daemon/execdriver/native/template"
  12. "github.com/docker/docker/pkg/idtools"
  13. "github.com/docker/docker/pkg/mount"
  14. "github.com/docker/go-units"
  15. "github.com/opencontainers/runc/libcontainer"
  16. "github.com/opencontainers/runc/libcontainer/cgroups/fs"
  17. "github.com/opencontainers/runc/libcontainer/configs"
  18. blkiodev "github.com/opencontainers/runc/libcontainer/configs"
  19. )
  20. // Mount contains information for a mount operation.
  21. type Mount struct {
  22. Source string `json:"source"`
  23. Destination string `json:"destination"`
  24. Writable bool `json:"writable"`
  25. Data string `json:"data"`
  26. Propagation string `json:"mountpropagation"`
  27. }
  28. // Resources contains all resource configs for a driver.
  29. // Currently these are all for cgroup configs.
  30. type Resources struct {
  31. CommonResources
  32. // Fields below here are platform specific
  33. BlkioWeightDevice []*blkiodev.WeightDevice `json:"blkio_weight_device"`
  34. BlkioThrottleReadBpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_bps_device"`
  35. BlkioThrottleWriteBpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_bps_device"`
  36. BlkioThrottleReadIOpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_iops_device"`
  37. BlkioThrottleWriteIOpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_iops_device"`
  38. MemorySwap int64 `json:"memory_swap"`
  39. KernelMemory int64 `json:"kernel_memory"`
  40. CPUQuota int64 `json:"cpu_quota"`
  41. CpusetCpus string `json:"cpuset_cpus"`
  42. CpusetMems string `json:"cpuset_mems"`
  43. CPUPeriod int64 `json:"cpu_period"`
  44. Rlimits []*units.Rlimit `json:"rlimits"`
  45. OomKillDisable bool `json:"oom_kill_disable"`
  46. MemorySwappiness int64 `json:"memory_swappiness"`
  47. }
  48. // ProcessConfig is the platform specific structure that describes a process
  49. // that will be run inside a container.
  50. type ProcessConfig struct {
  51. CommonProcessConfig
  52. // Fields below here are platform specific
  53. Privileged bool `json:"privileged"`
  54. User string `json:"user"`
  55. Console string `json:"-"` // dev/console path
  56. }
  57. // Ipc settings of the container
  58. // It is for IPC namespace setting. Usually different containers
  59. // have their own IPC namespace, however this specifies to use
  60. // an existing IPC namespace.
  61. // You can join the host's or a container's IPC namespace.
  62. type Ipc struct {
  63. ContainerID string `json:"container_id"` // id of the container to join ipc.
  64. HostIpc bool `json:"host_ipc"`
  65. }
  66. // Pid settings of the container
  67. // It is for PID namespace setting. Usually different containers
  68. // have their own PID namespace, however this specifies to use
  69. // an existing PID namespace.
  70. // Joining the host's PID namespace is currently the only supported
  71. // option.
  72. type Pid struct {
  73. HostPid bool `json:"host_pid"`
  74. }
  75. // UTS settings of the container
  76. // It is for UTS namespace setting. Usually different containers
  77. // have their own UTS namespace, however this specifies to use
  78. // an existing UTS namespace.
  79. // Joining the host's UTS namespace is currently the only supported
  80. // option.
  81. type UTS struct {
  82. HostUTS bool `json:"host_uts"`
  83. }
  84. // Network settings of the container
  85. type Network struct {
  86. Mtu int `json:"mtu"`
  87. ContainerID string `json:"container_id"` // id of the container to join network.
  88. NamespacePath string `json:"namespace_path"`
  89. HostNetworking bool `json:"host_networking"`
  90. }
  91. // Command wraps an os/exec.Cmd to add more metadata
  92. type Command struct {
  93. CommonCommand
  94. // Fields below here are platform specific
  95. AllowedDevices []*configs.Device `json:"allowed_devices"`
  96. AppArmorProfile string `json:"apparmor_profile"`
  97. AutoCreatedDevices []*configs.Device `json:"autocreated_devices"`
  98. CapAdd []string `json:"cap_add"`
  99. CapDrop []string `json:"cap_drop"`
  100. CgroupParent string `json:"cgroup_parent"` // The parent cgroup for this command.
  101. GIDMapping []idtools.IDMap `json:"gidmapping"`
  102. GroupAdd []string `json:"group_add"`
  103. Ipc *Ipc `json:"ipc"`
  104. OomScoreAdj int `json:"oom_score_adj"`
  105. Pid *Pid `json:"pid"`
  106. ReadonlyRootfs bool `json:"readonly_rootfs"`
  107. RemappedRoot *User `json:"remap_root"`
  108. SeccompProfile string `json:"seccomp_profile"`
  109. UIDMapping []idtools.IDMap `json:"uidmapping"`
  110. UTS *UTS `json:"uts"`
  111. }
  112. // SetRootPropagation sets the root mount propagation mode.
  113. func SetRootPropagation(config *configs.Config, propagation int) {
  114. config.RootPropagation = propagation
  115. }
  116. // InitContainer is the initialization of a container config.
  117. // It returns the initial configs for a container. It's mostly
  118. // defined by the default template.
  119. func InitContainer(c *Command) *configs.Config {
  120. container := template.New()
  121. container.Hostname = getEnv("HOSTNAME", c.ProcessConfig.Env)
  122. container.Cgroups.Name = c.ID
  123. container.Cgroups.Resources.AllowedDevices = c.AllowedDevices
  124. container.Devices = filterDevices(c.AutoCreatedDevices, (c.RemappedRoot.UID != 0))
  125. container.Rootfs = c.Rootfs
  126. container.Readonlyfs = c.ReadonlyRootfs
  127. // This can be overridden later by driver during mount setup based
  128. // on volume options
  129. SetRootPropagation(container, mount.RPRIVATE)
  130. container.Cgroups.Parent = c.CgroupParent
  131. // check to see if we are running in ramdisk to disable pivot root
  132. container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""
  133. return container
  134. }
  135. func filterDevices(devices []*configs.Device, userNamespacesEnabled bool) []*configs.Device {
  136. if !userNamespacesEnabled {
  137. return devices
  138. }
  139. filtered := []*configs.Device{}
  140. // if we have user namespaces enabled, these devices will not be created
  141. // because of the mknod limitation in the kernel for an unprivileged process.
  142. // Rather, they will be bind-mounted, which will only work if they exist;
  143. // check for existence and remove non-existent entries from the list
  144. for _, device := range devices {
  145. if _, err := os.Stat(device.Path); err == nil {
  146. filtered = append(filtered, device)
  147. }
  148. }
  149. return filtered
  150. }
  151. func getEnv(key string, env []string) string {
  152. for _, pair := range env {
  153. parts := strings.SplitN(pair, "=", 2)
  154. if parts[0] == key {
  155. return parts[1]
  156. }
  157. }
  158. return ""
  159. }
  160. // SetupCgroups setups cgroup resources for a container.
  161. func SetupCgroups(container *configs.Config, c *Command) error {
  162. if c.Resources != nil {
  163. container.Cgroups.Resources.CpuShares = c.Resources.CPUShares
  164. container.Cgroups.Resources.Memory = c.Resources.Memory
  165. container.Cgroups.Resources.MemoryReservation = c.Resources.MemoryReservation
  166. container.Cgroups.Resources.MemorySwap = c.Resources.MemorySwap
  167. container.Cgroups.Resources.KernelMemory = c.Resources.KernelMemory
  168. container.Cgroups.Resources.CpusetCpus = c.Resources.CpusetCpus
  169. container.Cgroups.Resources.CpusetMems = c.Resources.CpusetMems
  170. container.Cgroups.Resources.CpuPeriod = c.Resources.CPUPeriod
  171. container.Cgroups.Resources.CpuQuota = c.Resources.CPUQuota
  172. container.Cgroups.Resources.BlkioWeight = c.Resources.BlkioWeight
  173. container.Cgroups.Resources.BlkioWeightDevice = c.Resources.BlkioWeightDevice
  174. container.Cgroups.Resources.BlkioThrottleReadBpsDevice = c.Resources.BlkioThrottleReadBpsDevice
  175. container.Cgroups.Resources.BlkioThrottleWriteBpsDevice = c.Resources.BlkioThrottleWriteBpsDevice
  176. container.Cgroups.Resources.BlkioThrottleReadIOPSDevice = c.Resources.BlkioThrottleReadIOpsDevice
  177. container.Cgroups.Resources.BlkioThrottleWriteIOPSDevice = c.Resources.BlkioThrottleWriteIOpsDevice
  178. container.Cgroups.Resources.OomKillDisable = c.Resources.OomKillDisable
  179. container.Cgroups.Resources.MemorySwappiness = c.Resources.MemorySwappiness
  180. }
  181. return nil
  182. }
  183. // Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
  184. func getNetworkInterfaceStats(interfaceName string) (*libcontainer.NetworkInterface, error) {
  185. out := &libcontainer.NetworkInterface{Name: interfaceName}
  186. // This can happen if the network runtime information is missing - possible if the
  187. // container was created by an old version of libcontainer.
  188. if interfaceName == "" {
  189. return out, nil
  190. }
  191. type netStatsPair struct {
  192. // Where to write the output.
  193. Out *uint64
  194. // The network stats file to read.
  195. File string
  196. }
  197. // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
  198. netStats := []netStatsPair{
  199. {Out: &out.RxBytes, File: "tx_bytes"},
  200. {Out: &out.RxPackets, File: "tx_packets"},
  201. {Out: &out.RxErrors, File: "tx_errors"},
  202. {Out: &out.RxDropped, File: "tx_dropped"},
  203. {Out: &out.TxBytes, File: "rx_bytes"},
  204. {Out: &out.TxPackets, File: "rx_packets"},
  205. {Out: &out.TxErrors, File: "rx_errors"},
  206. {Out: &out.TxDropped, File: "rx_dropped"},
  207. }
  208. for _, netStat := range netStats {
  209. data, err := readSysfsNetworkStats(interfaceName, netStat.File)
  210. if err != nil {
  211. return nil, err
  212. }
  213. *(netStat.Out) = data
  214. }
  215. return out, nil
  216. }
  217. // Reads the specified statistics available under /sys/class/net/<EthInterface>/statistics
  218. func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
  219. data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
  220. if err != nil {
  221. return 0, err
  222. }
  223. return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
  224. }
  225. // Stats collects all the resource usage information from a container.
  226. func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) {
  227. f, err := os.Open(filepath.Join(containerDir, "state.json"))
  228. if err != nil {
  229. return nil, err
  230. }
  231. defer f.Close()
  232. type network struct {
  233. Type string
  234. HostInterfaceName string
  235. }
  236. state := struct {
  237. CgroupPaths map[string]string `json:"cgroup_paths"`
  238. Networks []network
  239. }{}
  240. if err := json.NewDecoder(f).Decode(&state); err != nil {
  241. return nil, err
  242. }
  243. now := time.Now()
  244. mgr := fs.Manager{Paths: state.CgroupPaths}
  245. cstats, err := mgr.GetStats()
  246. if err != nil {
  247. return nil, err
  248. }
  249. stats := &libcontainer.Stats{CgroupStats: cstats}
  250. // if the container does not have any memory limit specified set the
  251. // limit to the machines memory
  252. memoryLimit := containerMemoryLimit
  253. if memoryLimit == 0 {
  254. memoryLimit = machineMemory
  255. }
  256. for _, iface := range state.Networks {
  257. switch iface.Type {
  258. case "veth":
  259. istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
  260. if err != nil {
  261. return nil, err
  262. }
  263. stats.Interfaces = append(stats.Interfaces, istats)
  264. }
  265. }
  266. return &ResourceStats{
  267. Stats: stats,
  268. Read: now,
  269. MemoryLimit: memoryLimit,
  270. }, nil
  271. }
  272. // User contains the uid and gid representing a Unix user
  273. type User struct {
  274. UID int `json:"root_uid"`
  275. GID int `json:"root_gid"`
  276. }
  277. // ExitStatus provides exit reasons for a container.
  278. type ExitStatus struct {
  279. // The exit code with which the container exited.
  280. ExitCode int
  281. // Whether the container encountered an OOM.
  282. OOMKilled bool
  283. }