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)
python监控docker
最新推荐文章于 2024-06-30 14:00:00 发布