driver_unix.go 9.3 KB

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