# coding=utf-8
import re
import os
import commands
import json
import psutil
from pyExcelerator import * def execute(cmd):
status, output = commands.getstatusoutput(cmd)
if status != 0:
raise Exception('status is %s, output is %s' % (status, output))
return output def get_all_container_ids_name():
infos = execute("docker ps |awk '{print $1, $NF}'").split('\n')
all_ids = {}
regex = re.compile('\s+')
for info in infos:
docker_id, docker_name = regex.split(info)
short_id = docker_id.strip()
if short_id.strip().startswith('CON'):
continue
full_id = execute("docker inspect -f '{{.Id}}' %s" % short_id)
state = execute("cat /run/runc/%s/state.json" % full_id)
f = json.loads(state)
cgroup_paths = f['cgroup_paths']['pids']
pids_path = os.path.join(cgroup_paths, 'cgroup.procs')
ids = execute("cat %s" % pids_path).split('\n')
for prgress_id in ids:
pr_id = prgress_id.strip()
all_ids[pr_id] = {'id': short_id, 'name': docker_name}
return all_ids def get_process_info(p):
try:
# cpu = int(p.cpu_percent(interval=1))
rss = p.memory_info().rss
name = p.name()
pid = p.pid
return '%s,%s,%s\n' % (pid, name, rss)
except Exception as e:
print e.message def get_all_process_info():
"""取出全部进程的进程名,进程ID,进程实际内存, 虚拟内存,CPU使用率
"""
node_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'node_test.log')
instances = ''
all_processes = list(psutil.process_iter())
for proc in all_processes:
ret = get_process_info(proc)
if ret:
instances += ret
with open(node_name, 'w') as fp:
fp.writelines(instances) def get_docker_name():
file_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'node_test.log')
result_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.txt')
id_name_relation = get_all_container_ids_name()
tmp = ''
regex = re.compile(',')
with open(file_name, 'r') as fp:
for progress_info in fp.readlines():
progress_id, mem, progress_name = regex.split(progress_info)[0], regex.split(progress_info)[2], \
regex.split(progress_info)[1]
if progress_id in id_name_relation:
tmp += '%s %s %s %s %s\n' % (progress_id, id_name_relation[progress_id]['id'],
id_name_relation[progress_id]['name'], progress_name, mem)
else:
tmp += '%s %s %s %s %s\n' % (progress_id, 'sys_progress', 'sys_progress', progress_name, mem)
with open(result_name, 'w') as fp:
fp.writelines(tmp) def ge_excel():
file_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.txt')
result_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.xlsx')
regex = re.compile(' ')
w = Workbook() # 创建一个工作簿
ws = w.add_sheet('node_1_data') # 创建一个工作表
ws.write(0, 0, 'pid')
ws.write(0, 1, 'docker_id')
ws.write(0, 2, 'docker_name')
ws.write(0, 3, 'progress_name')
ws.write(0, 4, 'mem(MB)')
index = 1
with open(file_name, 'r') as fp:
for info in fp.readlines():
progress_info = info.strip()
if progress_info:
progress_id, docker_id, docker_name, progress_name, mem = regex.split(progress_info)
ws.write(index, 0, progress_id)
ws.write(index, 1, docker_id)
ws.write(index, 2, docker_name)
ws.write(index, 3, progress_name)
ws.write(index, 4, float(mem) / 1024 / 1024)
index += 1
w.save(result_name) def delete_tmp_file():
data_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.txt')
node_test_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'node_test.log')
if os.path.exists(data_name):
os.remove(data_name)
if os.path.exists(node_test_name):
os.remove(node_test_name) if __name__ == '__main__':
delete_tmp_file()
get_all_process_info()
get_docker_name()
ge_excel()
delete_tmp_file()

通过进程id找到进程对应的容器并统计每个进程的内存占用写到excel里的更多相关文章

  1. 采集容器内存并写到excel

    # coding=utf-8 import os import commands import re from pyExcelerator import * def execute(cmd): sta ...

  2. Linux/Unix分配进程ID的方法以及源代码实现

    在Linux/Unix系统中.每一个进程都有一个非负整型表示的唯一进程ID.尽管是唯一的.可是进程的ID能够重用.当一个进程终止后,其进程ID就能够再次使用了. 大多数Linux/Unix系统採用延迟 ...

  3. Linux进程间通信--进程,信号,管道,消息队列,信号量,共享内存

    Linux进程间通信--进程,信号,管道,消息队列,信号量,共享内存 参考:<linux编程从入门到精通>,<Linux C程序设计大全>,<unix环境高级编程> ...

  4. jstack:将Process Explorer中看到的进程ID做16进制转换,到ThreadDump中加上0x 前缀即能找到对应线程(转)

    原文链接:http://www.iteye.com/topic/1133941 症状: 使用Eclipse win 64位版本,indigo及kepler都重现了,使用tomcat 6.0.39,jd ...

  5. Linux 内核进程管理之进程ID

    Linux 内核使用 task_struct 数据结构来关联所有与进程有关的数据和结构,Linux 内核所有涉及到进程和程序的所有算法都是围绕该数据结构建立的,是内核中最重要的数据结构之一.该数据结构 ...

  6. Linux 内核进程管理之进程ID 。图解

    http://www.cnblogs.com/hazir/tag/kernel/ Linux 内核进程管理之进程ID   Linux 内核使用 task_struct 数据结构来关联所有与进程有关的数 ...

  7. Linux进程ID号--Linux进程的管理与调度(三)【转】

    Linux 内核使用 task_struct 数据结构来关联所有与进程有关的数据和结构,Linux 内核所有涉及到进程和程序的所有算法都是围绕该数据结构建立的,是内核中最重要的数据结构之一. 该数据结 ...

  8. Linux进程ID号--Linux进程的管理与调度(三)

    转自:http://blog.csdn.net/gatieme/article/category/6225543 日期 内核版本 架构 作者 GitHub CSDN 2016-05-12 Linux- ...

  9. Linux 内核进程管理之进程ID【转】

    转自:http://www.cnblogs.com/hazir/p/linux_kernel_pid.html Linux 内核使用 task_struct 数据结构来关联所有与进程有关的数据和结构, ...

随机推荐

  1. 多项式总结(unfinished)

    试试以二级标题为主的格式. 多项式相关 注:本篇博客不包含\(FFT\)基础姿势.如果您想要阅读本篇博客,请确保自己对\(FFT,NTT\)有基本的认识并且能够独立写出代码. 多项式是什么? 左转数学 ...

  2. RAC & MVVM 学习资料整理

    最后更新:2017-01-23 参考链接: MVVM奇葩说 MVVM 介绍 Model-View-ViewModel for iOS [译] 唐巧--被误解的 MVC 和被神化的 MVVM React ...

  3. [CSP-S模拟测试]:树(树上上升序列+主席树+线段树)

    题目传送门(内部题78) 输入格式 第一行输入两个整数$n,q$,表示节点数和询问数. 第二行输入$n$个整数$w_i$,表示第$i$个点的智商. 第三行至第$n+1$行每行输入两个数$x,y$,表示 ...

  4. 使用eclipse导入新项目时中文出现乱码问题

    有时候在github上看到别人不错的项目想要拉下来学习学习的时候,总会出现这样的情况,实在蛋疼. 一般出现这种问题,会有三个地方需要改动: 在项目上右键选择 properties 将 text fil ...

  5. linux sed 替换,使用变量,变量中含有特殊字符的处理

    文件 test.sh 内容如下: #!/bin/bash export JAVA_HOME=/data/jdk_1.9.0 echo $JAVA_HOME 想把 JAVA_HOME = 后面的内容替换 ...

  6. 禁止、允许MySQL root用户远程访问权限

    关闭MySQL root用户远程访问权限: use mysql; update user set host = "localhost" where user = "roo ...

  7. 阶段1 语言基础+高级_1-3-Java语言高级_08-JDK8新特性_第3节 两种获取Stream流的方式_11_练习:集合元素处理(Stream方式)

  8. 35 怎么优化join

    35 怎么优化join 上一篇介绍了join的两种算法:nlj和bnl create table t1(id int primary key, a int, b int, index(a)); cre ...

  9. 练习4-python+selenium+pandas

    最近对于python的第三方库pandas比较有兴趣,在学习的过程中也简单的结合selenium做了一个简单的小工具 最新公司用一个外部系统来记录,追踪BUG,可是这个系统并不是专业的BUG管理系统, ...

  10. Android.应用软件.常用程序下载地址_20190913

    1. 1.1. 健康友行 微信 官网 https://weixin.qq.com/ 抖音 chrome 百度网盘(账号:osskill)中有 1.2. 支付宝 官网 https://mobile.al ...