driver_unix.go 9.4 KB

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