driver_unix.go 9.0 KB

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