美文网首页Linux我用 LinuxDocker容器
如何计算容器的CPU使用值

如何计算容器的CPU使用值

作者: Aaaaaaaron | 来源:发表于2019-05-26 17:31 被阅读0次
    cpu

    因为监控系统调整需要,需要从宿主机获取容器的 CPU 使用率。

    以前在给容器分配 CPU 资源的时候,是绑定指定 CPU 的方式,那宿主只要计算不同容器绑定的 CPU 使用率即可。但是最近对 CPU 资源的分配方式进行了调整,通过CPU使用时间的方式对 CPU 使用率进行限制。(通过CPU使用时间限制有不少优势,另外写文章介绍。)

    原来的方法不再适用。既然 Cgroup 可以通过 CPU 时间对 CPU 资源进行限制,那必然在某个地方会统计 CPU 的使用时间。于是我在网络上搜索了一番,大部分的结果都是告诉我可以通过以下命令获取容器的 CPU 使用率。

    $ docker stats awesome_brattain 67b2525d8ad1
    
    CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
    b95a83497c91        awesome_brattain    0.28%               5.629MiB / 1.952GiB   0.28%               916B / 0B           147kB / 0B          9
    67b2525d8ad1        foobar              0.00%               1.727MiB / 1.952GiB   0.09%               2.48kB / 0B         4.11MB / 0B         2
    

    显然,现在一旦说到容器,基本上都会认为说的是 docker,其实我用的是LXC。不过不管怎样,计算方法应该是一致的。

    摸索一番,发现在以下路径就能找到一个容器(这里是LXC)的 CPU 使用时间,时间单位是纳秒:

    /sys/fs/cgroup/cpu/lxc/$lxc_name/cpuacct.usage
    

    利用这个时间,再计算实际经过的时间,就能得出在一段时间内,CPU的使用率。

    PS. 通过这个方法,不仅能计算整个 CPU 使用率,还可以计算出用户态和内核态分别使用的情况,在特定情况会更有助于了解应用程序的使用情况。(见cpuacct.usage_syscpuacct.usage_user)

    计算方法

    CPU 使用率 = (结束时CPU使用时间 - 开始时CPU使用时间) / (结束时间 - 开始时间)
    

    CPU使用时间就是上一节文中提到的cgroup文件下的cpuacct.usage文件里的时间。

    当前时间,以纳秒计算,可以通过以下函数获取:

    import time
    import subporcess
    
    def get_current_time(self):
        """get current time in nanoseconds
        """
        try:
            # time_ns() only supported by python 3.7
            time = time.time_ns()
        except Exception:
            time = subprocess.check_output(['date', '+%s%N'])
    
        return int(time)
    

    只要两个时间点的当前时间相减,就可以得到总共经过的时间了。

    这个程序的源码也可以贴出来,有需要的朋友也可以去Github上可克隆:
    https://github.com/aaron0769/lxc-cpu-usage

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    # Author: shanhanqiang
    
    import time
    import sys
    import subprocess
    
    
    class CPU():
    
        def __init__(self, cpuacct_file):
            self.cpuacct_file = cpuacct_file
            self.last_total_time = self.get_total_time()
            self.last_use_time = self.get_use_time()
    
        def get_total_time(self):
            """get total time elapsed, in nanoseconds
            """
            try:
                # time_ns() only supported by python 3.7
                total_time = time.time_ns()
            except Exception:
                total_time = subprocess.check_output(['date', '+%s%N'])
    
            return int(total_time)
    
        def get_use_time(self):
            """get use time elapsed, in nanoseconds
            """
            with open(self.cpuacct_file, 'r') as f:
                use_time = int(f.read())
            return use_time
    
        def get_cpu_usage(self):
            current_total_time = self.get_total_time()
            current_use_time = self.get_use_time()
    
            delta_use_time = current_use_time - self.last_use_time
            delta_total_time = current_total_time - self.last_total_time
            usage = delta_use_time / delta_total_time
    
            self.last_total_time = current_total_time
            self.last_use_time = current_use_time
    
            return usage
    
    def main():
    
        if len(sys.argv) < 2:
            print("Error: need a name of lxc")
            print("python cpu_usage.py lxc_name")
    
        lxc_name = sys.argv[1]
        cpuacct_usage_file = "/sys/fs/cgroup/cpu/lxc/{}/cpuacct.usage".format(lxc_name)
        cpu = CPU(cpuacct_usage_file)
        while True:
            cpu_usage = round(cpu.get_cpu_usage() * 100, 2)
            print("{} CPU Usage: {}".format(lxc_name, cpu_usage))
            time.sleep(1)
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

        本文标题:如何计算容器的CPU使用值

        本文链接:https://www.haomeiwen.com/subject/rblftctx.html