6dae4b867916187807ad95e34dfc43d69863b711
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2007 Guillaume Chazarain <guichaz@gmail.com>
19 # Allow printing with same syntax in Python 2/3
20 from __future__
import print_function
32 # Check for requirements:
33 # o Linux >= 2.6.20 with I/O accounting and VM event counters
34 # o Python >= 2.5 or Python 2.4 + ctypes
37 ioaccounting
= os
.path
.exists('/proc/self/io')
47 from iotop
.vmstat
import VmStat
50 vm_event_counters
= False
52 vm_event_counters
= True
54 if not ioaccounting
or not has_ctypes
or not vm_event_counters
:
55 print('Could not run iotop as some of the requirements are not met:')
56 if not ioaccounting
or not vm_event_counters
:
57 print('- Linux >= 2.6.20 with')
59 print(' - I/O accounting support ' \
60 '(CONFIG_TASKSTATS, CONFIG_TASK_DELAY_ACCT, ' \
61 'CONFIG_TASK_IO_ACCOUNTING)')
62 if not vm_event_counters
:
63 print(' - VM event counters (CONFIG_VM_EVENT_COUNTERS)')
65 print('- Python >= 2.5 or Python 2.4 with the ctypes module')
69 from iotop
import ioprio
, vmstat
70 from iotop
.netlink
import Connection
, NETLINK_GENERIC
, U32Attr
, NLM_F_REQUEST
71 from iotop
.genetlink
import Controller
, GeNlMessage
73 class DumpableObject(object):
74 """Base class for all objects that allows easy introspection when printed"""
76 return '%s: %s>' % (str(type(self
))[:-1], pprint
.pformat(self
.__dict
__))
80 # Interesting fields in a taskstats output
83 class Stats(DumpableObject
):
85 ('blkio_delay_total', 40),
86 ('swapin_delay_total', 56),
89 ('cancelled_write_bytes', 264)
92 has_blkio_delay_total
= False
94 def __init__(self
, task_stats_buffer
):
96 for name
, offset
in Stats
.members_offsets
:
97 data
= task_stats_buffer
[offset
:offset
+ 8]
98 sd
[name
] = struct
.unpack('Q', data
)[0]
100 # This is a heuristic to detect if CONFIG_TASK_DELAY_ACCT is enabled in
102 if not Stats
.has_blkio_delay_total
:
103 Stats
.has_blkio_delay_total
= self
.blkio_delay_total
!= 0
105 def accumulate(self
, other_stats
, destination
, coeff
=1):
106 """Update destination from operator(self, other_stats)"""
107 dd
= destination
.__dict
__
109 od
= other_stats
.__dict
__
110 for member
, offset
in Stats
.members_offsets
:
111 dd
[member
] = sd
[member
] + coeff
* od
[member
]
113 def delta(self
, other_stats
, destination
):
114 """Update destination with self - other_stats"""
115 return self
.accumulate(other_stats
, destination
, coeff
=-1)
117 def is_all_zero(self
):
119 for name
, offset
in Stats
.members_offsets
:
125 def build_all_zero():
126 stats
= Stats
.__new
__(Stats
)
128 for name
, offset
in Stats
.members_offsets
:
133 # Netlink usage for taskstats
136 TASKSTATS_CMD_GET
= 1
137 TASKSTATS_CMD_ATTR_PID
= 1
138 TASKSTATS_TYPE_AGGR_PID
= 4
139 TASKSTATS_TYPE_PID
= 1
140 TASKSTATS_TYPE_STATS
= 3
142 class TaskStatsNetlink(object):
143 # Keep in sync with format_stats() and pinfo.did_some_io()
145 def __init__(self
, options
):
146 self
.options
= options
147 self
.connection
= Connection(NETLINK_GENERIC
)
148 controller
= Controller(self
.connection
)
149 self
.family_id
= controller
.get_family_id('TASKSTATS')
151 def build_request(self
, tid
):
152 return GeNlMessage(self
.family_id
, cmd
=TASKSTATS_CMD_GET
,
153 attrs
=[U32Attr(TASKSTATS_CMD_ATTR_PID
, tid
)],
156 def get_single_task_stats(self
, thread
):
157 thread
.task_stats_request
.send(self
.connection
)
159 reply
= GeNlMessage
.recv(self
.connection
)
161 if e
.errno
== errno
.ESRCH
:
162 # OSError: Netlink error: No such process (3)
165 for attr_type
, attr_value
in reply
.attrs
.items():
166 if attr_type
== TASKSTATS_TYPE_AGGR_PID
:
167 reply
= attr_value
.nested()
171 taskstats_data
= reply
[TASKSTATS_TYPE_STATS
].data
172 if len(taskstats_data
) < 272:
175 taskstats_version
= struct
.unpack('H', taskstats_data
[:2])[0]
176 assert taskstats_version
>= 4
177 return Stats(taskstats_data
)
183 def find_uids(options
):
184 """Build options.uids from options.users by resolving usernames to UIDs"""
187 for u
in options
.users
or []:
192 passwd
= pwd
.getpwnam(u
)
194 print('Unknown user:', u
, file=sys
.stderr
)
199 options
.uids
.append(uid
)
204 def parse_proc_pid_status(pid
):
207 for line
in open('/proc/%d/status' % pid
):
208 key
, value
= line
.split(':\t', 1)
209 result_dict
[key
] = value
.strip()
211 pass # No such process
215 def safe_utf8_decode(s
):
217 return s
.decode('utf-8')
218 except UnicodeDecodeError:
219 return s
.encode('string_escape')
220 except AttributeError:
223 class ThreadInfo(DumpableObject
):
224 """Stats for a single thread"""
225 def __init__(self
, tid
, taskstats_connection
):
228 self
.stats_total
= None
229 self
.stats_delta
= Stats
.__new
__(Stats
)
230 self
.task_stats_request
= taskstats_connection
.build_request(tid
)
232 def get_ioprio(self
):
233 return ioprio
.get(self
.tid
)
235 def set_ioprio(self
, ioprio_class
, ioprio_data
):
236 return ioprio
.set_ioprio(ioprio
.IOPRIO_WHO_PROCESS
, self
.tid
,
237 ioprio_class
, ioprio_data
)
239 def update_stats(self
, stats
):
240 if not self
.stats_total
:
241 self
.stats_total
= stats
242 stats
.delta(self
.stats_total
, self
.stats_delta
)
243 self
.stats_total
= stats
246 class ProcessInfo(DumpableObject
):
247 """Stats for a single process (a single line in the output): if
248 options.processes is set, it is a collection of threads, otherwise a single
250 def __init__(self
, pid
):
254 self
.threads
= {} # {tid: ThreadInfo}
255 self
.stats_delta
= Stats
.build_all_zero()
256 self
.stats_accum
= Stats
.build_all_zero()
257 self
.stats_accum_timestamp
= time
.time()
259 def is_monitored(self
, options
):
260 if (options
.pids
and not options
.processes
and
261 self
.pid
not in options
.pids
):
262 # We only monitor some threads, not this one
265 if options
.uids
and self
.get_uid() not in options
.uids
:
266 # We only monitor some users, not this one
274 # uid in (None, 0) means either we don't know the UID yet or the process
275 # runs as root so it can change its UID. In both cases it means we have
276 # to find out its current UID.
278 uid
= os
.stat('/proc/%d' % self
.pid
)[stat
.ST_UID
]
280 # The process disappeared
283 # Maybe the process called setuid()
290 if uid
is not None and not self
.user
:
292 self
.user
= safe_utf8_decode(pwd
.getpwuid(uid
).pw_name
)
293 except (KeyError, AttributeError):
295 return self
.user
or '{none}'
297 def get_cmdline(self
):
298 # A process may exec, so we must always reread its cmdline
300 proc_cmdline
= open('/proc/%d/cmdline' % self
.pid
)
301 cmdline
= proc_cmdline
.read(4096)
303 return '{no such process}'
304 proc_status
= parse_proc_pid_status(self
.pid
)
306 # Probably a kernel thread, get its name from /proc/PID/status
307 proc_status_name
= proc_status
.get('Name', '')
309 proc_status_name
= '[%s]' % proc_status_name
311 proc_status_name
= '{no name}'
312 return proc_status_name
314 tgid
= int(proc_status
.get('Tgid', self
.pid
))
316 # Not the main thread, maybe it has a custom name
317 tgid_name
= parse_proc_pid_status(tgid
).get('Name', '')
318 thread_name
= proc_status
.get('Name', '')
319 if thread_name
!= tgid_name
:
320 suffix
+= ' [%s]' % thread_name
321 parts
= cmdline
.split('\0')
322 if parts
[0].startswith('/'):
323 first_command_char
= parts
[0].rfind('/') + 1
324 parts
[0] = parts
[0][first_command_char
:]
325 cmdline
= ' '.join(parts
).strip()
326 return safe_utf8_decode(cmdline
+ suffix
)
328 def did_some_io(self
, accumulated
):
330 return not self
.stats_accum
.is_all_zero()
331 for t
in self
.threads
.values():
332 if not t
.stats_delta
.is_all_zero():
336 def get_ioprio(self
):
337 priorities
= set(t
.get_ioprio() for t
in self
.threads
.values())
338 if len(priorities
) == 1:
339 return priorities
.pop()
342 def set_ioprio(self
, ioprio_class
, ioprio_data
):
343 for thread
in self
.threads
.values():
344 thread
.set_ioprio(ioprio_class
, ioprio_data
)
346 def ioprio_sort_key(self
):
347 return ioprio
.sort_key(self
.get_ioprio())
349 def get_thread(self
, tid
, taskstats_connection
):
350 thread
= self
.threads
.get(tid
, None)
352 thread
= ThreadInfo(tid
, taskstats_connection
)
353 self
.threads
[tid
] = thread
356 def update_stats(self
):
357 stats_delta
= Stats
.build_all_zero()
358 for tid
, thread
in self
.threads
.items():
360 stats_delta
.accumulate(thread
.stats_delta
, stats_delta
)
361 self
.threads
= dict([(tid
, thread
) for tid
, thread
in
362 self
.threads
.items() if not thread
.mark
])
364 nr_threads
= len(self
.threads
)
368 stats_delta
.blkio_delay_total
/= nr_threads
369 stats_delta
.swapin_delay_total
/= nr_threads
371 self
.stats_delta
= stats_delta
372 self
.stats_accum
.accumulate(self
.stats_delta
, self
.stats_accum
)
376 class ProcessList(DumpableObject
):
377 def __init__(self
, taskstats_connection
, options
):
380 self
.taskstats_connection
= taskstats_connection
381 self
.options
= options
382 self
.timestamp
= time
.time()
383 self
.vmstat
= vmstat
.VmStat()
385 # A first time as we are interested in the delta
386 self
.update_process_counts()
388 def get_process(self
, pid
):
389 """Either get the specified PID from self.processes or build a new
390 ProcessInfo if we see this PID for the first time"""
391 process
= self
.processes
.get(pid
, None)
393 process
= ProcessInfo(pid
)
394 self
.processes
[pid
] = process
396 if process
.is_monitored(self
.options
):
399 def list_tgids(self
):
400 if self
.options
.pids
:
401 return self
.options
.pids
403 tgids
= os
.listdir('/proc')
404 if self
.options
.processes
:
405 return [int(tgid
) for tgid
in tgids
if '0' <= tgid
[0] <= '9']
409 if '0' <= tgid
[0] <= '9':
411 tids
.extend(map(int, os
.listdir('/proc/' + tgid
+ '/task')))
417 def list_tids(self
, tgid
):
418 if not self
.options
.processes
:
422 tids
= list(map(int, os
.listdir('/proc/%d/task' % tgid
)))
426 if self
.options
.pids
:
427 tids
= list(set(self
.options
.pids
).intersection(set(tids
)))
431 def update_process_counts(self
):
432 new_timestamp
= time
.time()
433 self
.duration
= new_timestamp
- self
.timestamp
434 self
.timestamp
= new_timestamp
436 total_read
= total_write
= 0
438 for tgid
in self
.list_tgids():
439 process
= self
.get_process(tgid
)
442 for tid
in self
.list_tids(tgid
):
443 thread
= process
.get_thread(tid
, self
.taskstats_connection
)
444 stats
= self
.taskstats_connection
.get_single_task_stats(thread
)
446 thread
.update_stats(stats
)
447 delta
= thread
.stats_delta
448 total_read
+= delta
.read_bytes
449 total_write
+= delta
.write_bytes
451 return (total_read
, total_write
), self
.vmstat
.delta()
453 def refresh_processes(self
):
454 for process
in self
.processes
.values():
455 for thread
in process
.threads
.values():
458 total_read_and_write
= self
.update_process_counts()
460 self
.processes
= dict([(pid
, process
) for pid
, process
in
461 self
.processes
.items() if
462 process
.update_stats()])
464 return total_read_and_write