python监控docker

import docker
import subprocess
import time
#https://docker-py.readthedocs.io/en/stable/containers.html
class Dockermnage():
    def __init__(self):
        self.client = docker.DockerClient(base_url='unix://var/run/docker.sock')
        # client = docker.from_env()
    def containerlist(self):
        containers = self.client.containers.list(all = True)
        Containers = [{'name':container.name, "image":container.image,'status':container.status} for container in containers]
        return Containers

    def getcontainer(self, containername):
         return self.client.containers.get(containername)

    def containerlog(self,containername, timestamps = True, tail = 'all', since = None, until = None, ):

        container = self.getcontainer(containername)
        content = container.logs(timestamps= timestamps, tail = tail, since= since, until = until)
        return content

    def log_container(self,containername):
        #实时读取日志
        pos = 0
        while 1:
            num = 0
            print('reading..........')
            out = subprocess.Popen('docker logs -t {}'.format(containername), shell= True, stdout= subprocess.PIPE)
            logs = out.stdout.readlines()[pos:]
            out.terminate()
            for i in logs:
                d = bytes.decode(i).replace('\r\n', '')
                if len(d) > 40:
                    print(d)
                num += 1
            pos += num
         #   time.sleep(1)


    def run_container(self,image, command=None, **kwargs):
        #client.containers.run('alpine', 'echo hello world')
        newcontainer = self.client.containers.run(image, command=None, **kwargs)

    def pause_container(self, containername):
        container = self.getcontainer(containername)
        container.pasue()

    def remove_container(self, containername):
        container = self.getcontainer(containername)
        container.remove()

    def stop_container(self,containername):
        container = self.getcontainer(containername)
        container.stop()

    def top_container(self, containername):
        container = self.getcontainer(containername)
        top = container.top()
        print(top)
        return top
    def stats_container(self,containername):
        #Stream statistics for this container. Similar to the docker stats command.
        container = self.getcontainer(containername)
        stats = container.stats(decode =True)
        statsvalue = next(stats)
        timestamp = statsvalue['read'][:-11]
        pids_num = statsvalue['pids_stats']['current']
        networks = statsvalue['networks']['eth0']
        out = subprocess.Popen('docker stats {}'.format(containername), shell=True,stdout=subprocess.PIPE)
        for n,v in enumerate(out.stdout):
            if n == 1:
                value = bytes.decode(v.strip()).split(' ')
                valuelist = [j for j in value if j != '' and j !='/']
                valuelist[2], valuelist[5] = float(valuelist[2][:-1]), float(valuelist[5][:-1])
                monitordict = dict(zip(['cpu_percentage',  'memory_useage', 'memory_total', 'memory_percentage', 'net_in', 'net_out', 'block_in', 'block_out'],valuelist[2:]))
                out.terminate()
                break
        monitordict.update({'timestamp':timestamp,'pids_num':pids_num,'networks':networks})
        print(monitordict)
        return monitordict
if __name__ == '__main__':
    doc = Dockermnage()
    while 1:
        containers = doc.containerlist()
        for i in containers:
            if i['status'] == 'running':
                containername = i['name']
                Dict = doc.stats_container(containername)
                dict1 = doc.top_container(containername)
                Dict.update(dict1)
                with open('/home/dnxx/myproject/Docker/{}.log'.format(containername), 'a') as file:
                    file.write(json.dumps(Dict) + '\n')
        time.sleep(3)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值