More verbose error handling for this exception:
[iotop.git] / iotop / ui.py
blobe9e722f8871b1e426a86b041b320d44a24abe17d
1 import curses
2 import errno
3 import locale
4 import optparse
5 import os
6 import pwd
7 import select
8 import struct
9 import sys
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):
23 base = 1 << (10 * i)
24 if 2 * base < size:
25 break
26 else:
27 i = 0
28 base = 1
29 res = '%.2f %s/s' % ((float(bw) / base), UNITS[i])
30 return res
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
46 # The UI
49 class IOTopUI(object):
50 # key, reverse
51 sorting_keys = [
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
69 self.sorting_key = 5
70 self.sorting_reverse = IOTopUI.sorting_keys[5][1]
71 if not self.options.batch:
72 self.win = win
73 self.resize()
74 try:
75 curses.use_default_colors()
76 curses.start_color()
77 curses.curs_set(0)
78 except curses.error:
79 # This call can fail with misconfigured terminals, for example
80 # TERM=xterm-color. This is harmless
81 pass
83 def resize(self):
84 self.height, self.width = self.win.getmaxyx()
86 def run(self):
87 iterations = 0
88 poll = select.poll()
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:
98 iterations += 1
99 if iterations >= self.options.iterations:
100 break
102 try:
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:
106 events = 0
107 else:
108 raise
109 if not self.options.batch:
110 self.resize()
111 if events:
112 key = self.win.getch()
113 self.handle_key(key)
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
129 key_bindings = {
130 ord('q'):
131 lambda: sys.exit(0),
132 ord('Q'):
133 lambda: sys.exit(0),
134 ord('r'):
135 lambda: self.reverse_sorting(),
136 ord('R'):
137 lambda: self.reverse_sorting(),
138 ord('o'):
139 toggle_only_io,
140 curses.KEY_LEFT:
141 lambda: self.adjust_sorting_key(-1),
142 curses.KEY_RIGHT:
143 lambda: self.adjust_sorting_key(1),
144 curses.KEY_HOME:
145 lambda: self.adjust_sorting_key(-len(IOTopUI.sorting_keys)),
146 curses.KEY_END:
147 lambda: self.adjust_sorting_key(len(IOTopUI.sorting_keys))
150 action = key_bindings.get(key, lambda: None)
151 action()
153 def get_data(self):
154 def format(p):
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]
162 return line
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:
183 print summary
184 print ''.join(titles)
185 for l in lines:
186 print l
187 else:
188 self.win.erase()
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
193 title = titles[i]
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)):
199 try:
200 self.win.addstr(i + 2, 0, lines[i].encode('utf-8'))
201 except curses.error:
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
206 self.win.refresh()
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)
212 ui.run()
215 # Main program
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]
227 def main():
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',
236 metavar='NUM',
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',
246 dest='processes',
247 help='only show processes, not all threads')
248 options, args = parser.parse_args()
249 if args:
250 parser.error('Unexpected arguments: ' + ' '.join(args))
251 find_uids(options)
252 options.pids = options.pids or []
253 if options.batch:
254 run_iotop(None, options)
255 else:
256 curses.wrapper(run_iotop, options)