# 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. idea中svn代码冲突

    1.鼠标右键点击项目根目录 --> 2.选择 subversion --> 3.resolve Text Confict --> 4.merge 手动编辑冲突部分,解决后就能正常提交 ...

  2. iOS即时通讯之CocoaAsyncSocket源码解析一

    申明:本文内容属于转载整理,原文连接 前言: CocoaAsyncSocket是谷歌的开发者,基于BSD-Socket写的一个IM框架,它给Mac和iOS提供了易于使用的.强大的异步套接字库,向上封装 ...

  3. Gitblit 添加密钥实现客户端无密码pull、push代码

    之前管理代码用的是SVN,项目需要将管理代码软件切换为Git 折腾了一天,记录下遇到的小坑,方便后来人. 服务端 服务端 的系统是Windows Sever2008 ,首先在服务端安装window版本 ...

  4. (转)用C#实现实现简单的 Ping 的功能,用于测试网络是否已经连通

    本文转载自:http://blog.csdn.net/xiamin/archive/2009/02/14/3889696.aspx 用C#实现实现简单的 Ping 的功能,用于测试网络是否已经联通 1 ...

  5. Celery多任务结构

    视图结构 pro_cel ├── celery_task# celery相关文件夹 │ ├── celery.py # celery连接和配置相关文件,必须叫这个名字 │ └── tasks1.py ...

  6. 错误 error: The following untracked working tree files would be overwritten by merge:README.md

    问题类型 相信很多小伙伴在创建新的git仓库后,会选上添加README.md文件,开始我也没太在意,应该也没有什么问题. 但是当我通过git添加远程仓库,给这个仓库上传代码时,出现了如下问题:erro ...

  7. C#之委托(一)

    1,什么是委托 简单来说,就是代码在恰当的时间执行一段操作.代码不需要操作的细节.举个例子,遗嘱为例.一般来说遗嘱是在某人去世之前写好,然后把它放发到一个安全的地方,去世之后然后律师会执行遗嘱中的指令 ...

  8. 百度地图转腾讯地图腾讯地图转百度地图(还有方法二就是使用百度地图api 转火星坐标)

    public static double pi = 3.141592653589793 * 3000.0 / 180.0; /** * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转 ...

  9. pandas 入门(3)

    from pandas import Series, DataFrame, Index import numpy as np # 层次化索引 对数据重塑和分组操作很有用 data = Series(n ...

  10. CSS浏览器兼容性

    答题技巧:因为这个问题主要是看你经验,一般有了开发经验的都会遇到这样的坑,你只要说出几个来大致就可以了. 1.对齐文本和文本输入框 问题: 当input元素在设置了高时,在IE7.IE8.IE9下会出 ...