11 from iotop
.data
import find_uids
, TaskStatsNetlink
, ProcessList
12 from iotop
.version
import VERSION
15 # Utility functions for the UI
18 UNITS
= ['B', 'K', 'M', 'G', 'T', 'P', 'E']
20 def human_bandwidth(size
, duration
):
21 bw
= size
and float(size
) / duration
22 for i
in xrange(len(UNITS
) - 1, 0, -1):
29 res
= '%.2f %s/s' % ((float(bw
) / base
), UNITS
[i
])
32 def human_stats(stats
, duration
):
33 # Keep in sync with TaskStatsNetlink.members_offsets and
34 # IOTopUI.get_data(self)
35 def delay2percent(delay
): # delay in ns, duration in s
36 return '%.2f %%' % min(99.99, delay
/ (duration
* 10000000.0))
37 io_delay
= delay2percent(stats
.blkio_delay_total
)
38 swapin_delay
= delay2percent(stats
.swapin_delay_total
)
39 read_bytes
= human_bandwidth(stats
.read_bytes
, duration
)
40 written_bytes
= stats
.write_bytes
- stats
.cancelled_write_bytes
41 written_bytes
= max(0, written_bytes
)
42 write_bytes
= human_bandwidth(written_bytes
, duration
)
43 return io_delay
, swapin_delay
, read_bytes
, write_bytes
49 class IOTopUI(object):
52 (lambda p
: p
.pid
, False),
53 (lambda p
: p
.user
, False),
54 (lambda p
: p
.stats_delta
.read_bytes
, True),
55 (lambda p
: p
.stats_delta
.write_bytes
-
56 p
.stats_delta
.cancelled_write_bytes
, True),
57 (lambda p
: p
.stats_delta
.swapin_delay_total
, True),
58 # The default sorting (by I/O % time) should show processes doing
59 # only writes, without waiting on them
60 (lambda p
: p
.stats_delta
.blkio_delay_total
or
61 int(not(not(p
.stats_delta
.read_bytes
or
62 p
.stats_delta
.write_bytes
))), True),
63 (lambda p
: p
.get_cmdline(), False),
66 def __init__(self
, win
, process_list
, options
):
67 self
.process_list
= process_list
68 self
.options
= options
70 self
.sorting_reverse
= IOTopUI
.sorting_keys
[5][1]
71 if not self
.options
.batch
:
75 curses
.use_default_colors()
79 # This call can fail with misconfigured terminals, for example
80 # TERM=xterm-color. This is harmless
84 self
.height
, self
.width
= self
.win
.getmaxyx()
89 if not self
.options
.batch
:
90 poll
.register(sys
.stdin
.fileno(), select
.POLLIN|select
.POLLPRI
)
91 while self
.options
.iterations
is None or \
92 iterations
< self
.options
.iterations
:
93 total
= self
.process_list
.refresh_processes()
94 total_read
, total_write
= total
95 self
.refresh_display(total_read
, total_write
,
96 self
.process_list
.duration
)
97 if self
.options
.iterations
is not None:
99 if iterations
>= self
.options
.iterations
:
103 events
= poll
.poll(self
.options
.delay_seconds
* 1000.0)
104 except select
.error
, e
:
105 if e
.args
and e
.args
[0] == errno
.EINTR
:
109 if not self
.options
.batch
:
112 key
= self
.win
.getch()
115 def reverse_sorting(self
):
116 self
.sorting_reverse
= not self
.sorting_reverse
118 def adjust_sorting_key(self
, delta
):
119 orig_sorting_key
= self
.sorting_key
120 self
.sorting_key
+= delta
121 self
.sorting_key
= max(0, self
.sorting_key
)
122 self
.sorting_key
= min(len(IOTopUI
.sorting_keys
) - 1, self
.sorting_key
)
123 if orig_sorting_key
!= self
.sorting_key
:
124 self
.sorting_reverse
= IOTopUI
.sorting_keys
[self
.sorting_key
][1]
126 def handle_key(self
, key
):
127 def toggle_only_io():
128 self
.options
.only ^
= True
135 lambda: self
.reverse_sorting(),
137 lambda: self
.reverse_sorting(),
141 lambda: self
.adjust_sorting_key(-1),
143 lambda: self
.adjust_sorting_key(1),
145 lambda: self
.adjust_sorting_key(-len(IOTopUI
.sorting_keys
)),
147 lambda: self
.adjust_sorting_key(len(IOTopUI
.sorting_keys
))
150 action
= key_bindings
.get(key
, lambda: None)
155 stats
= human_stats(p
.stats_delta
, self
.process_list
.duration
)
156 io_delay
, swapin_delay
, read_bytes
, write_bytes
= stats
157 line
= '%5d %-8s %11s %11s %7s %7s ' % (p
.pid
, p
.user
[:8],
158 read_bytes
, write_bytes
, swapin_delay
, io_delay
)
159 line
+= p
.get_cmdline()
160 if not self
.options
.batch
:
161 line
= line
[:self
.width
- 1]
164 def should_format(p
):
165 return not self
.options
.only
or p
.did_some_io()
167 processes
= self
.process_list
.processes
.values()
168 processes
= filter(should_format
, processes
)
169 key
= IOTopUI
.sorting_keys
[self
.sorting_key
][0]
170 processes
.sort(key
=key
, reverse
=self
.sorting_reverse
)
171 if not self
.options
.batch
:
172 del processes
[self
.height
- 2:]
173 return map(format
, processes
)
175 def refresh_display(self
, total_read
, total_write
, duration
):
176 summary
= 'Total DISK READ: %s | Total DISK WRITE: %s' % (
177 human_bandwidth(total_read
, duration
),
178 human_bandwidth(total_write
, duration
))
179 titles
= [' PID', ' USER', ' DISK READ', ' DISK WRITE',
180 ' SWAPIN', ' IO', ' COMMAND']
181 lines
= self
.get_data()
182 if self
.options
.batch
:
184 print ''.join(titles
)
189 self
.win
.addstr(summary
)
190 self
.win
.hline(1, 0, ord(' ') | curses
.A_REVERSE
, self
.width
)
191 for i
in xrange(len(titles
)):
192 attr
= curses
.A_REVERSE
194 if i
== self
.sorting_key
:
195 attr |
= curses
.A_BOLD
196 title
+= self
.sorting_reverse
and '>' or '<'
197 self
.win
.addstr(title
, attr
)
198 for i
in xrange(len(lines
)):
200 self
.win
.addstr(i
+ 2, 0, lines
[i
].encode('utf-8'))
202 exc_type
, value
, traceback
= sys
.exc_info()
203 value
= '%s win:%s i:%d line:%s' % \
204 (value
, self
.win
.getmaxyx(), i
, lines
[i
])
205 raise exc_type
, value
.encode('string_escape'), traceback
208 def run_iotop(win
, options
):
209 taskstats_connection
= TaskStatsNetlink(options
)
210 process_list
= ProcessList(taskstats_connection
, options
)
211 ui
= IOTopUI(win
, process_list
, options
)
218 USAGE
= '''%s [OPTIONS]
220 DISK READ and DISK WRITE are the block I/O bandwidth used during the sampling
221 period. SWAPIN and IO are the percentages of time the thread spent respectively
222 while swapping in and waiting on I/O more generally.
223 Controls: left and right arrows to change the sorting column, r to invert the
224 sorting order, o to toggle the --only option, q to quit, any other key to force
225 a refresh.''' % sys
.argv
[0]
228 locale
.setlocale(locale
.LC_ALL
, '')
229 parser
= optparse
.OptionParser(usage
=USAGE
, version
='iotop ' + VERSION
)
230 parser
.add_option('-o', '--only', action
='store_true',
231 dest
='only', default
=False,
232 help='only show processes or threads actually doing I/O')
233 parser
.add_option('-b', '--batch', action
='store_true', dest
='batch',
234 help='non-interactive mode')
235 parser
.add_option('-n', '--iter', type='int', dest
='iterations',
237 help='number of iterations before ending [infinite]')
238 parser
.add_option('-d', '--delay', type='float', dest
='delay_seconds',
239 help='delay between iterations [1 second]',
240 metavar
='SEC', default
=1)
241 parser
.add_option('-p', '--pid', type='int', dest
='pids', action
='append',
242 help='processes/threads to monitor [all]', metavar
='PID')
243 parser
.add_option('-u', '--user', type='str', dest
='users', action
='append',
244 help='users to monitor [all]', metavar
='USER')
245 parser
.add_option('-P', '--processes', action
='store_true',
247 help='only show processes, not all threads')
248 options
, args
= parser
.parse_args()
250 parser
.error('Unexpected arguments: ' + ' '.join(args
))
252 options
.pids
= options
.pids
or []
254 run_iotop(None, options
)
256 curses
.wrapper(run_iotop
, options
)