通过docker远程API获取各个节点的资源使用情况
调用dokcer引擎的http://localhost:2375/contains/{id}/stats
curl http://localhost:2375/containers/stats/
//参数strem=0 代表静态获取一次容器的使用数据
curl http://localhost:2375/containers/node0/stats?stream=0
使用wsl在Linux系统中通过Docker Engine的API获取容器的资源使用情况
1.在Linux系统中打开终端,安装curl工具
sudo apt-get install curl
2.使用以下命令获取Docker Engine的API版本
curl --unix-socket /var/run/docker.sock http:/v1.42/version
该命令将返回Docker Engine的API版本号。
3.使用以下命令获取特定容器的资源使用情况
curl --unix-socket /var/run/docker.sock http:/v1.24/containers/<container_id>/stats?stream=0
获取容器资源使用情况的各个指标
1.根据url获取容器的资源使用情况,返回字节数组类型的数据
exec.Command("curl", "--unix-socket", "/var/run/docker.sock", "http:/v1.42/containers/node0/stats?stream=false").Output()
2.解析为json格式数据
stats := make(map[string]interface{})
err = json.Unmarshal(out, &stats)
3.解析计算指标所需的数据
cpuStats := stats["cpu_stats"].(map[string]interface{})
cpuUsage := cpuStats["cpu_usage"].(map[string]interface{})
totalUsage := cpuUsage["total_usage"].(float64)
systemUsage := cpuStats["system_cpu_usage"].(float64)
4.计算指标值
cpuPercent := 0.0
numCores := float64(len(cpuUsage["percpu_usage"].([]interface{})))
if numCores > 0 {
cpuPercent = (totalUsage / systemUsage) * numCores * 100.0
}
示例代码如下:
func getrsfromexec() {
out, err := exec.Command("curl", "--unix-socket", "/var/run/docker.sock", "http:/v1.42/containers/node0/stats?stream=false").Output()
if err != nil {
log.Fatal(err)
}
stats := make(map[string]interface{})
err = json.Unmarshal(out, &stats)
if err != nil {
log.Fatal(err)
}
cpuStats := stats["cpu_stats"].(map[string]interface{})
cpuUsage := cpuStats["cpu_usage"].(map[string]interface{})
totalUsage := cpuUsage["total_usage"].(float64)
systemUsage := cpuStats["system_cpu_usage"].(float64)
cpuPercent := 0.0
numCores := float64(len(cpuUsage["percpu_usage"].([]interface{})))
if numCores > 0 {
cpuPercent = (totalUsage / systemUsage) * numCores * 100.0
}
fmt.Printf("CPU Usage: %.2f%%\n", cpuPercent)
}