pythonモニタdocker

12630 ワード

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
'
, '') 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 !='/'] 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 c = Dockermnage() c.log_container('centos')