Debian Codegraph @

ptrace/linux_proc.py

raw
1 """
2 Functions and variables to access to Linux proc directory.
3
4 Constant:
5
6 - PAGE_SIZE: size of a memory page
7 """
8 from os import readlink, listdir
9 from resource import getpagesize
10 from ptrace.tools import timestampUNIX
11 from datetime import timedelta
12
13 PAGE_SIZE = getpagesize()
14
15
16 class ProcError(Exception):
17 """
18 Linux proc directory error.
19 """
20 pass
21
22
23 def openProc(path):
24 """
25 Open a proc entry in read only mode.
26 """
27 filename = "/proc/%s" % path
28 try:
29 return open(filename)
30 except IOError as err:
31 raise ProcError("Unable to open %r: %s" % (filename, err))
32
33
34 def readProc(path):
35 """
36 Read the content of a proc entry.
37 Eg. readProc("stat") to read /proc/stat.
38 """
39 with openProc(path) as procfile:
40 return procfile.read()
41
42
43 def readProcessProc(pid, key):
44 """
45 Read the content of a process entry in the proc directory.
46 Eg. readProcessProc(pid, "status") to read /proc/pid/status.
47 """
48 try:
49 filename = "/proc/%s/%s" % (pid, key)
50 with open(filename) as proc:
51 return proc.read()
52 except IOError as err:
53 raise ProcError("Process %s doesn't exist: %s" % (pid, err))
54
55
56 class ProcessState(object):
57 """
58 Processus state. Attributes:
59 - state (str): process status ('R', 'S', 'T', ...)
60 - program (str): program name
61 - pid (int): process identifier
62 - ppid (int): parent process identifier
63 - pgrp (int): process group
64 - session (int): session identifier
65 - tty_nr (int): tty number
66 - tpgid (int)
67 - utime (int): user space time (jiffies)
68 - stime (int): kernel space time (jiffies)
69 - starttime (int): start time
70 """
71 STATE_NAMES = {
72 "R": "running",
73 "S": "sleeping",
74 "D": "disk",
75 "Z": "zombie",
76 "T": "traced",
77 "W": "paging",
78 }
79
80 def __init__(self, stat):
81 # pid (program) ... => "pid (program", "..."
82 part, stat = stat.rsplit(')', 1)
83 self.pid, self.program = part.split('(', 1)
84 self.pid = int(self.pid)
85
86 # "state ..." => state, "..."
87 stat = stat.split()
88 self.state = stat[0]
89 stat = [int(item) for item in stat[1:]]
90
91 # Read next numbers
92 self.ppid = stat[0]
93 self.pgrp = stat[1]
94 self.session = stat[2]
95 self.tty_nr = stat[3]
96 self.tpgid = stat[4]
97 self.utime = stat[10]
98 self.stime = stat[11]
99 self.starttime = stat[18]
100
101
102 def readProcessStat(pid):
103 """
104 Read the process state ('stat') as a ProcessState object.
105 """
106 stat = readProcessProc(pid, 'stat')
107 return ProcessState(stat)
108
109
110 def readProcessStatm(pid):
111 """
112 Read the process memory status ('statm') as a list of integers.
113 Values are in bytes (and not in pages).
114 """
115 statm = readProcessProc(pid, 'statm')
116 statm = [int(item) * PAGE_SIZE for item in statm.split()]
117 return statm
118
119
120 def readProcessProcList(pid, key):
121 """
122 Read a process entry as a list of strings.
123 """
124 data = readProcessProc(pid, key)
125 if not data:
126 # Empty file: empty list
127 return []
128 data = data.split("\0")
129 if not data[-1]:
130 del data[-1]
131 return data
132
133
134 def readProcessLink(pid, key):
135 """
136 Read a process link.
137 """
138 try:
139 filename = "/proc/%s/%s" % (pid, key)
140 return readlink(filename)
141 except OSError as err:
142 raise ProcError("Unable to read proc link %r: %s" % (filename, err))
143
144
145 def readProcesses():
146 """
147 Read all processes identifiers. The function is a generator,
148 use it with: ::
149
150 for pid in readProcesses(): ...
151 """
152 for filename in listdir('/proc'):
153 try:
154 yield int(filename)
155 except ValueError:
156 # Filename is not an integer (e.g. "stat" from /proc/stat)
157 continue
158
159
160 def readProcessCmdline(pid, escape_stat=True):
161 """
162 Read the process command line. If escape_stat is True, format program name
163 with "[%s]" if the process has no command line, e.g. "[khelper]".
164 """
165 # Try /proc/42/cmdline
166 try:
167 cmdline = readProcessProcList(pid, 'cmdline')
168 if cmdline:
169 return cmdline
170 except ProcError:
171 pass
172
173 # Try /proc/42/stat
174 try:
175 stat = readProcessStat(pid)
176 program = stat.program
177 if escape_stat:
178 program = "[%s]" % program
179 return [program]
180 except ProcError:
181 return None
182
183
184 def searchProcessesByName(process_name):
185 """
186 Find all processes matching the program name pattern.
187 Eg. pattern "ssh" will find the program "/usr/bin/ssh".
188
189 This function is a generator yielding the process identifier,
190 use it with: ::
191
192 for pid in searchProcessByName(pattern):
193 ...
194 """
195 suffix = '/' + process_name
196 for pid in readProcesses():
197 cmdline = readProcessCmdline(pid)
198 if not cmdline:
199 continue
200 program = cmdline[0]
201 if program == process_name or program.endswith(suffix):
202 yield pid
203
204
205 def searchProcessByName(process_name):
206 """
207 Function similar to searchProcessesByName() but only return the identifier
208 of the first matching process. Raise a ProcError if there is no matching
209 process.
210 """
211 for pid in searchProcessesByName(process_name):
212 return pid
213 raise ProcError("Unable to find process: %r" % process_name)
214
215
216 def getUptime():
217 """
218 Get the system uptime as a datetime.timedelta object.
219 """
220 uptime = readProc('uptime')
221 uptime = uptime.strip().split()
222 uptime = float(uptime[0])
223 return timedelta(seconds=uptime)
224
225
226 def getSystemBoot():
227 """
228 Get the system boot date as a datetime.datetime object.
229 """
230 if getSystemBoot.value is None:
231 stat_file = openProc('stat')
232 for line in stat_file:
233 if not line.startswith("btime "):
234 continue
235 seconds = int(line[6:])
236 btime = timestampUNIX(seconds, True)
237 getSystemBoot.value = btime
238 break
239 stat_file.close()
240 if getSystemBoot.value is None:
241 raise ProcError("Unable to read system boot time!")
242 return getSystemBoot.value
243
244
245 getSystemBoot.value = None