-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy patheos_process_monitor.py
More file actions
executable file
·89 lines (69 loc) · 2.46 KB
/
Copy patheos_process_monitor.py
File metadata and controls
executable file
·89 lines (69 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import psutil
import init_work_home
init_work_home.init()
from config.config import Config
from utils.logger import logger
from utils.metric import Metric
pname = Config.get_process_name()
memory_total_bytes = float(psutil.virtual_memory().total)
memory_total_gb = memory_total_bytes / 1024 / 1024 / 1024
class Monitor:
def __init__(self, pname):
self.pname = str(pname)
self.pid = None
def init_pid(self):
try:
for p in psutil.process_iter():
if p.name().lower() == self.pname.lower():
self.pid = p.pid
break
except Exception as e:
logger.error(e)
if self.pid is None:
raise Exception(('process(%s) not exists' % self.pname))
def init_process(self):
global process
self.init_pid()
process = psutil.Process(self.pid)
def memory(self):
memory_percent = process.memory_percent()
memory_usage_gb = round(memory_total_gb * memory_percent / 100, 2)
memory_percent = round(memory_percent, 2)
self.metric_collect(Metric.memory_percent, memory_percent)
self.metric_collect(Metric.memory_usage, memory_usage_gb)
def cpu(self):
cpu_usage_percent = process.cpu_percent(interval=1)
cpu_usage_percent = round(cpu_usage_percent, 2)
self.metric_collect(Metric.cpu_percent, cpu_usage_percent)
def connections(self):
connections = psutil.net_connections('tcp')
connection_count = 0
for sconn in connections:
if self.pid == sconn.pid:
connection_count = connection_count + 1
self.metric_collect(Metric.connections, connection_count)
def metric_collect(self, key, value):
logger.info("%s %s %s" % (self.pid, key, value))
Metric.metric(key, value)
def monitor(self):
try:
self.init_process()
self.cpu()
self.memory()
self.connections()
except Exception as e:
logger.error('process monitor error: %s', e)
def usage():
global pname
parser = argparse.ArgumentParser(description='process cpu/ram/connections monitor tool.')
parser.add_argument('-n', '--pname', default=pname, help='process name')
args = parser.parse_args()
pname = args.pname
def main():
Monitor(pname).monitor()
if __name__ == '__main__':
usage()
main()