# 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. 使用M/Monit进行可视化集中进程管理

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://heqin.blog.51cto.com/8931355/1863924 一:前言 ...

  2. Django REST framework入门 (转自中文文档)

    快速入门 我们将创建一个简单的允许管理员用户查看和编辑系统中的用户和组的API. 项目设置 创建一个名为 tutorial 的新django项目,然后启动一个名为 quickstart 的新app. ...

  3. apache cgi 程序: End of script output before headers

    测试linux Apache cgi程序: #include <stdio.h> int main(){ printf("abc"); ; } 目录:/var/www/ ...

  4. ORACLE查询隐含参数

    查询隐含参数:col name for a30col VALUE for a10col DESCRIB for a40set lines 200SELECT x.ksppinm NAME, y.ksp ...

  5. redispy

    w wuser@ubuntu:~/redispy$ redis-cli > keys * ) "w" ) "wpy" > set w1 w1valu ...

  6. tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

    在执行自动化打包的时候报错,检查发现是Xcode的路径被改了 标记3的地方原来默认是没有内容的,点击它,然后会自动弹出一个选项,就是xcode的版本. 修改后,在命令行输入xcodebuild命令测试 ...

  7. python-笔记(六)模块操作以及常用模块简介

    模块.包 什么是模块? 模块实质上就是一个python文件,它是用来组织代码的,意思是说把python代码写到里面,文件名就是模块的名称,例如:model.py model就是模块名称. 什么是包? ...

  8. 项目开源-基于ASP.NET Core和EF Core的快速开发框架

    前言:作为一名95后的程序猿,已经写了一年多的代码了,为了提升自己的技术水平,所以决定尝试编写一个快速开发框架开源出来,一来提升自己的技术水平,二来助力.NET Core生态发展 写这个框架主要是为了 ...

  9. Linux_DNS服务器

    目录 目录 DNS DNS Server ServerSite Master DNS Server Forward Domain Reverse Resolution Slave DNS Server ...

  10. 【ABAP系列】SAP VA02修改销售订单的BAPI举例

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP VA02修改销售订单的B ...