driver_unix.go 9.3 KB

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