Go语言Docker API实战:获取Docker概览信息

本文将解析一段Go代码,该代码使用Docker API获取Docker的概览信息,包括容器数量、镜像数量、数据卷大小、CPU使用率和内存使用率等。

func (srv *OverviewService) ObtainOverviewInfo() (*dto.OverviewDto, error) {
	logger.Info('obtain overview info start...')
	var overviewDto dto.OverviewDto
	info, err := srv.cli.Info(context.Background())
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	overviewDto.ContainerCount = info.ContainersRunning
	overviewDto.ImageCount = info.Images
	cmd := exec.Command('du', '-sb', info.DockerRootDir)
	out, err := cmd.Output()
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	sizeStr := strings.Fields(string(out))[0]
	size, err := strconv.ParseInt(sizeStr, 10, 64)
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	//overviewDto.DataVolume = float64(size) / (1024 * 1024 * 1024)
	overviewDto.DataVolume = float64(size)
	containers, err := srv.cli.ContainerList(context.Background(), types.ContainerListOptions{})
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	if len(containers) > 0 {
		var list []dto.OverviewContainer
		var containerMemory uint64
		var containerCpuUsed uint64
		var containerTotalMemory uint64
		for _, container := range containers {
			stats, err := srv.cli.ContainerStats(context.Background(), container.ID, false)
			if err != nil {
				logger.Error(err.Error())
				return nil, err
			}
			all, err := io.ReadAll(stats.Body)
			if err != nil {
				logger.Error(err.Error())
				return nil, err
			}
			err = stats.Body.Close()
			if err != nil {
				logger.Error(err.Error())
				return nil, err
			}
			var statsDto types.StatsJSON
			err = json.Unmarshal(all, &statsDto)
			if err != nil {
				logger.Error(err.Error())
				return nil, err
			}
			var containerResp dto.OverviewContainer
			var memPercent float64
			if statsDto.MemoryStats.Usage > 0 {
				memPercent = (float64(statsDto.MemoryStats.Usage) / float64(statsDto.MemoryStats.Limit)) * 100.0
			}
			containerResp.CreatTime = time.Now().Unix()
			containerResp.MemoryUsagePercentage = strconv.FormatFloat(memPercent, 'f', 6, 64)
			cpuUsage := srv.calculateCPUPercentUnix(&statsDto.CPUStats, &statsDto.PreCPUStats)
			containerResp.CpuUsagePercentage = strconv.FormatFloat(cpuUsage, 'f', 6, 64)
			containerResp.ContainerName = statsDto.Name
			if len(statsDto.Networks) > 0 {
				for _, val := range statsDto.Networks {
					containerResp.UpstreamTraffic += val.RxBytes
					containerResp.DownstreamTraffic += val.TxBytes
				}
			}
			containerCpuUsed += statsDto.CPUStats.CPUUsage.TotalUsage - statsDto.PreCPUStats.CPUUsage.TotalUsage
			containerMemory += statsDto.MemoryStats.Usage
			containerTotalMemory += statsDto.MemoryStats.MaxUsage
			list = append(list, containerResp)
		}
		overviewDto.OverviewContainers = list
		//overviewDto.ContainerMemory = containerMemory / (1024 * 1024 * 1024)
		overviewDto.ContainerMemory = containerMemory
		overviewDto.ContainerCpuUsed = containerCpuUsed
		overviewDto.ContainerTotalMemory = containerTotalMemory
	}
	return &overviewDto, nil
}

代码解析:

  1. 获取基本信息:

    • 使用 srv.cli.Info(context.Background()) 获取 Docker 守护进程的信息,包括运行中的容器数量 (ContainersRunning) 和镜像数量 (Images),并将它们存储在 overviewDto 结构体中。
    • 使用 exec.Command('du', '-sb', info.DockerRootDir) 命令获取 Docker 根目录的大小,并将其转换为 GB 为单位的浮点数存储在 overviewDto.DataVolume 中。
  2. 获取容器信息:

    • 使用 srv.cli.ContainerList(context.Background(), types.ContainerListOptions{}) 获取所有容器的列表。
    • 遍历容器列表,针对每个容器执行以下操作:
      • 使用 srv.cli.ContainerStats(context.Background(), container.ID, false) 获取容器的统计信息,包括 CPU 和内存使用情况。
      • 使用 srv.calculateCPUPercentUnix 方法计算容器的 CPU 使用百分比,并将结果存储在 containerResp.CpuUsagePercentage 中。
      • 计算容器的内存使用百分比,并将结果存储在 containerResp.MemoryUsagePercentage 中。
      • 将容器的网络流量统计信息(上行和下行流量)存储在 containerResp.UpstreamTraffic 和 containerResp.DownstreamTraffic 中。
      • 将容器的 CPU 使用量、内存使用量和总内存量分别累加到 containerCpuUsed、containerMemory 和 containerTotalMemory 中。
      • 将容器的统计信息存储在 containerResp 结构体中,并将其添加到 list 切片中。
  3. 返回概览信息:

    • 将所有容器的统计信息列表 list 存储在 overviewDto.OverviewContainers 中。
    • 将总的 CPU 使用量、内存使用量和总内存量存储在 overviewDto.ContainerCpuUsed、overviewDto.ContainerMemory 和 overviewDto.ContainerTotalMemory 中。
    • 返回包含所有概览信息的 overviewDto 结构体指针。

总结:

这段代码演示了如何使用 Go 语言和 Docker API 获取 Docker 的概览信息,并提供了一些计算关键指标(如 CPU 和内存使用率)的方法。您可以根据自己的需要修改和扩展这段代码,以获取更多 Docker 统计信息。

Go语言Docker API实战:获取Docker概览信息

原文地址: https://www.cveoy.top/t/topic/fyUB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录