driver_unix.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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/docker/pkg/ulimit"
  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 []*ulimit.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.AllowedDevices = c.AllowedDevices
  124. container.Devices = c.AutoCreatedDevices
  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. // check to see if we are running in ramdisk to disable pivot root
  131. container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""
  132. // Default parent cgroup is "docker". Override if required.
  133. if c.CgroupParent != "" {
  134. container.Cgroups.Parent = c.CgroupParent
  135. }
  136. return container
  137. }
  138. func getEnv(key string, env []string) string {
  139. for _, pair := range env {
  140. parts := strings.SplitN(pair, "=", 2)
  141. if parts[0] == key {
  142. return parts[1]
  143. }
  144. }
  145. return ""
  146. }
  147. // SetupCgroups setups cgroup resources for a container.
  148. func SetupCgroups(container *configs.Config, c *Command) error {
  149. if c.Resources != nil {
  150. container.Cgroups.CpuShares = c.Resources.CPUShares
  151. container.Cgroups.Memory = c.Resources.Memory
  152. container.Cgroups.MemoryReservation = c.Resources.MemoryReservation
  153. container.Cgroups.MemorySwap = c.Resources.MemorySwap
  154. container.Cgroups.KernelMemory = c.Resources.KernelMemory
  155. container.Cgroups.CpusetCpus = c.Resources.CpusetCpus
  156. container.Cgroups.CpusetMems = c.Resources.CpusetMems
  157. container.Cgroups.CpuPeriod = c.Resources.CPUPeriod
  158. container.Cgroups.CpuQuota = c.Resources.CPUQuota
  159. container.Cgroups.BlkioWeight = c.Resources.BlkioWeight
  160. container.Cgroups.BlkioWeightDevice = c.Resources.BlkioWeightDevice
  161. container.Cgroups.BlkioThrottleReadBpsDevice = c.Resources.BlkioThrottleReadBpsDevice
  162. container.Cgroups.BlkioThrottleWriteBpsDevice = c.Resources.BlkioThrottleWriteBpsDevice
  163. container.Cgroups.BlkioThrottleReadIOPSDevice = c.Resources.BlkioThrottleReadIOpsDevice
  164. container.Cgroups.BlkioThrottleWriteIOPSDevice = c.Resources.BlkioThrottleWriteIOpsDevice
  165. container.Cgroups.OomKillDisable = c.Resources.OomKillDisable
  166. container.Cgroups.MemorySwappiness = c.Resources.MemorySwappiness
  167. }
  168. return nil
  169. }
  170. // Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
  171. func getNetworkInterfaceStats(interfaceName string) (*libcontainer.NetworkInterface, error) {
  172. out := &libcontainer.NetworkInterface{Name: interfaceName}
  173. // This can happen if the network runtime information is missing - possible if the
  174. // container was created by an old version of libcontainer.
  175. if interfaceName == "" {
  176. return out, nil
  177. }
  178. type netStatsPair struct {
  179. // Where to write the output.
  180. Out *uint64
  181. // The network stats file to read.
  182. File string
  183. }
  184. // 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.
  185. netStats := []netStatsPair{
  186. {Out: &out.RxBytes, File: "tx_bytes"},
  187. {Out: &out.RxPackets, File: "tx_packets"},
  188. {Out: &out.RxErrors, File: "tx_errors"},
  189. {Out: &out.RxDropped, File: "tx_dropped"},
  190. {Out: &out.TxBytes, File: "rx_bytes"},
  191. {Out: &out.TxPackets, File: "rx_packets"},
  192. {Out: &out.TxErrors, File: "rx_errors"},
  193. {Out: &out.TxDropped, File: "rx_dropped"},
  194. }
  195. for _, netStat := range netStats {
  196. data, err := readSysfsNetworkStats(interfaceName, netStat.File)
  197. if err != nil {
  198. return nil, err
  199. }
  200. *(netStat.Out) = data
  201. }
  202. return out, nil
  203. }
  204. // Reads the specified statistics available under /sys/class/net/<EthInterface>/statistics
  205. func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
  206. data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
  207. if err != nil {
  208. return 0, err
  209. }
  210. return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
  211. }
  212. // Stats collects all the resource usage information from a container.
  213. func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) {
  214. f, err := os.Open(filepath.Join(containerDir, "state.json"))
  215. if err != nil {
  216. return nil, err
  217. }
  218. defer f.Close()
  219. type network struct {
  220. Type string
  221. HostInterfaceName string
  222. }
  223. state := struct {
  224. CgroupPaths map[string]string `json:"cgroup_paths"`
  225. Networks []network
  226. }{}
  227. if err := json.NewDecoder(f).Decode(&state); err != nil {
  228. return nil, err
  229. }
  230. now := time.Now()
  231. mgr := fs.Manager{Paths: state.CgroupPaths}
  232. cstats, err := mgr.GetStats()
  233. if err != nil {
  234. return nil, err
  235. }
  236. stats := &libcontainer.Stats{CgroupStats: cstats}
  237. // if the container does not have any memory limit specified set the
  238. // limit to the machines memory
  239. memoryLimit := containerMemoryLimit
  240. if memoryLimit == 0 {
  241. memoryLimit = machineMemory
  242. }
  243. for _, iface := range state.Networks {
  244. switch iface.Type {
  245. case "veth":
  246. istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
  247. if err != nil {
  248. return nil, err
  249. }
  250. stats.Interfaces = append(stats.Interfaces, istats)
  251. }
  252. }
  253. return &ResourceStats{
  254. Stats: stats,
  255. Read: now,
  256. MemoryLimit: memoryLimit,
  257. }, nil
  258. }
  259. // User contains the uid and gid representing a Unix user
  260. type User struct {
  261. UID int `json:"root_uid"`
  262. GID int `json:"root_gid"`
  263. }
  264. // ExitStatus provides exit reasons for a container.
  265. type ExitStatus struct {
  266. // The exit code with which the container exited.
  267. ExitCode int
  268. // Whether the container encountered an OOM.
  269. OOMKilled bool
  270. }